从 Swift 2 开始,现在可以通过以下方式实现协议扩展,
为符合类型提供方法和属性实现
(可选地受到附加约束的限制)。
一个简单的例子:为所有符合的类型定义一个方法
到SequenceType
(例如Array
) 其中序列元素是String
:
extension SequenceType where Generator.Element == String {
func joined() -> String {
return "".join(self)
}
}
let a = ["foo", "bar"].joined()
print(a) // foobar
无法定义扩展方法struct Array
直接,但仅适用于所有类型
符合某些协议(具有可选约束)。那么一个
必须找到一个协议Array
符合并提供所有必要的方法。上面的例子中,也就是SequenceType
.
另一个例子(如何在 Swift 中将元素插入到排序数组的正确位置? https://stackoverflow.com/questions/26678362/how-do-i-insert-an-element-at-the-correct-position-into-a-sorted-array-in-swift):
extension CollectionType where Generator.Element : Comparable, Index : RandomAccessIndexType {
typealias T = Generator.Element
func insertionIndexOf(elem: T) -> Index {
var lo = self.startIndex
var hi = self.endIndex
while lo != hi {
// mid = lo + (hi - 1 - lo)/2
let mid = lo.advancedBy(lo.distanceTo(hi.predecessor())/2)
if self[mid] < elem {
lo = mid + 1
} else if elem < self[mid] {
hi = mid
} else {
return mid // found at position `mid`
}
}
return lo // not found, would be inserted at position `lo`
}
}
let ar = [1, 3, 5, 7]
let pos = ar.insertionIndexOf(6)
print(pos) // 3
这里该方法被定义为扩展CollectionType
因为
需要对元素进行下标访问,并且元素是
必须是Comparable
.