小编典典

是否可以在Swift中进行仅限于一类的Array扩展?

swift

我是否可以制作仅适用于字符串的Array扩展?


阅读 317

收藏
2020-07-07

共1个答案

小编典典

从Swift 2开始,这可以通过 协议扩展 来实现,该 协议扩展 为符合类型的类型(可选地受其他约束限制)提供方法和属性实现。

一个简单的例子:为所有符合SequenceType(例如Array)的类型定义一个方法,其中sequence元素为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的排序数组中?:

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

2020-07-07