gpt4 book ai didi

arrays - 是否可以在 Swift 中创建一个仅限于一个类的数组扩展?

转载 作者:搜寻专家 更新时间:2023-11-01 05:40:46 25 4
gpt4 key购买 nike

我可以做一个只适用于字符串的数组扩展吗?

最佳答案

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

一个简单的例子:为所有符合的类型定义一个方法到 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定义扩展方法,只能为所有类型定义符合某些协议(protocol)(具有可选约束)。所以一个必须找到 Array 符合并提供所有必要方法的协议(protocol)。在上面的示例中,即 SequenceType

另一个示例(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

关于arrays - 是否可以在 Swift 中创建一个仅限于一个类的数组扩展?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30794827/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com