美文网首页
Swift- 泛型

Swift- 泛型

作者: lxl125z | 来源:发表于2017-02-21 18:32 被阅读0次

    系统泛型

    例如:NSDictionary,NSArray

    Dictionary<String,Int>()
    Array<Int>()
    

    泛型函数

    func fanTest<T>(value:T)->T{
        
        print(value)
        return value
    }
    fanTest(value: "1")
    
    

    类型参数

    始终使用大写字母开头的驼峰命名法(例如 T 和 MyTypeParameter)来为类型参数命名,以表明它们是占位类型,而不是一个值。

    //类型参数
    func fanTest_2<T,U>(value:T,value2:U)->T{
        
        print(value)
        return value
    }
    fanTest_2(value: "1", value2: 1)
    

    泛型类型

    自定义类、结构体和枚举可以适用于任何类型,类似于 Array 和 Dictionary

    //泛型类型(自定义类、结构体和枚举)
    struct Stack<Element> {
        var items = [Element]()
        mutating func push(_ item: Element) {
            items.append(item)
        }
        mutating func pop() -> Element {
            return items.removeLast()
        }
    }
    
    

    扩展一个泛型类型

    extension Stack{
        
        var name:Element?{
            
            return nil
        }
    }
    

    类型约束

    类型参数名后面放置一个类名或者协议名

    func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
        // 这里是泛型函数的函数体部分
    }
    
    

    关联类型

    关联类型为协议中的某个类型提供了一个占位名(或者说别名),其代表的实际类型在协议被采纳时才会被指定。

    protocol Container {
        associatedtype ItemType
        mutating func append(_ item: ItemType)
        var count: Int { get }
        subscript(i: Int) -> ItemType { get }
    }
    
    
    struct testAAA:Container{
        typealias ItemType = Int   //协议实现的时候去定义类型
        internal subscript(i: Int) -> Int {
            return 1
        }
        var count: Int = 2
        mutating func append(_ item: ItemType){
        }
        
    }
    
    

    扩展一个已存在的类型来指定关联类型

    
    extension Array: Container {}
    
    

    泛型 Where 语句

    func allItemsMatch<C1: Container, C2: Container>
        (_ someContainer: C1, _ anotherContainer: C2) -> Bool
        where C1.ItemType == C2.ItemType, C1.ItemType: Equatable {
            
            // 检查两个容器含有相同数量的元素
            if someContainer.count != anotherContainer.count {
                return false
            }
            
            // 检查每一对元素是否相等
            for i in 0..<someContainer.count {
                if someContainer[i] != anotherContainer[i] {
                    return false
                }
            }
            // 所有元素都匹配,返回 true
            return true
    }
    
    func testBBB<T>(value:T) where T:Equatable {
        
        
    }
    
    

    相关文章

      网友评论

          本文标题:Swift- 泛型

          本文链接:https://www.haomeiwen.com/subject/bybuwttx.html