Swift语法基础:7

在前面, 我们知道了Swift中的Protocol和Extensions, 现在我们来看看另一个东西: Generics(泛型)


1.泛型的声明以及简单使用

func repeat <ItemType> (item:ItemType, times:Int) -> [ItemType] {
    var result = [ItemType]()

    for i in 0..<times {
        result.append(item)
    }
    return result
}
let a = repeat("knock", 4)
println(a)
// 打印出来的结果: [knock, knock, knock, knock]

PS: 所谓的泛型其实就是一个比较特殊的数组,它可以存储不同类型的数据, 这样子我们在写方法的时候, 就不需要再写多一个相同功能而类型不同的方法了.


2.枚举类型中的泛型

enum OptionalValue <T> {
    case None
    case Some(T)
}
var possibleInteger: OptionalValue <Int> = .None
possibleInteger = .Some(100)

3.特定需求的泛型

func anyCommonElements <T, U where T: SequenceType, U: SequenceType, T.Generator.Element: Equatable, T.Generator.Element == U.Generator.Element> (lhs: T, rhs: U) -> Bool {
    for lhsItem in lhs {
        for rhsItem in rhs {
            if lhsItem == rhsItem {
                return true
            }
        }
    }
    return false
}

var any = anyCommonElements([1, 2, 3], [9])
println(any)
// 打印出来的结果: false

PS: 如果你需要某个指定样式的泛型, 那么就必须得在泛型里加上where这个关键字.

4.泛型的另一种写法

func someFunction<T: SequenceType, U: SequenceType>(someT: T, someU: U) {
//     function body goes here
}

PS: 在泛型中, 其实它有另外一种写法:< T: Equatable>, 它是和 < T where T: Equatable>这种写法等价的, 而例子中的SequenceType是系统定义好的, 所以在这里不能随便乱写.


好了, 这次就讲到这里, 下次我们继续~~

原文地址:https://www.cnblogs.com/iOSCain/p/4333131.html