一,泛型
学过c++的人应该对泛型印象深刻,这是个非常方便的特性
1,用法
泛型主要用到函数、类/结构体上
func swapTwoValues<T>(inout a: T, inout b: T) {
let temporaryA = a
a = b
b = temporaryA
}
inout这个是输入输出参数
2,类型参数
上面的T,我们叫做类型参数
类型参数可以包含多个,每个类型参数之间用, 隔开
类型参数不止是T,还可以用其他字符代替。
3,类型约束
这个主要用在对类型参数的限制
虽然编译器不会检查类型参数的类型,但是我们可以让其规定继承某个类或者协议,强制要求其必须满足某些条件,语法如下
func someFunction<T: SomeClass, U: SomeProtocol>(someT: T, someU: U) {
// function body goes here
}
4,关联类型
这里主要提供代码
protocol Container {
typealias ItemType //关联类型
mutating func append(item: ItemType)
var count: Int { get }
subscript(i: Int) -> ItemType { get }
}
简单地说,关联类型就是在协议中,某些地方可能需要用到其他类型,但是暂时还无法确定这到底是什么类型(其实跟泛型是一个意思,只是用在协议上)
5,泛型中的where语句
很好理解,看代码
func allItemsMatch<
C1: Container, C2: Container
where C1.ItemType == C2.ItemType, C1.ItemType: Equatable>
(someContainer: C1, anotherContainer: C2) -> Bool {
// check that both containers contain the same number of items
if someContainer.count != anotherContainer.count {
return false
}
// check each pair of items to see if they are equivalent
for i in 0..someContainer.count {
if someContainer[i] != anotherContainer[i] {
return false
}
}
// all items match, so return true
return true
}
where可以在泛型中添加一些比较高级的约束