问题描述
我可以适用于,例如数组延伸,只是字符串?
Can I make an Array extension that applies to, for instance, just Strings?
推荐答案
随着斯威夫特2,这现在可以使用的实现协议扩展的,
它提供了方法和属性的实现,以符合类型
(任选被附加约束的限制)。
As of Swift 2, this can now be achieved with protocol extensions,which provide method and property implementations to conforming types(optionally restricted by additional constraints).
一个简单的例子:定义符合所有类型的方法
到序列类型
(如阵列
)其中的序列元素是字符串
:
A simple example: Define a method for all types conformingto SequenceType
(such as Array
) where the sequence element is a String
:
extension SequenceType where Generator.Element == String {
func joined() -> String {
return "".join(self)
}
}
let a = ["foo", "bar"].joined()
print(a) // foobar
扩展方法不能用于结构数组定义
直接,但仅限于所有类型
符合某种协议(带有可选的约束)。所以一
必须找到哪个阵列
符合并提供所有必要的方法的协议。在上面的例子中,即序列类型
The extension method cannot be defined for struct Array
directly, but only for all typesconforming to some protocol (with optional constraints). So onehas to find a protocol to which Array
conforms and which provides all the necessary methods. In the above example, that is SequenceType
.
另一个例子(的How我插在正确的位置处的元素到斯威夫特排序后的数组):
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
,因为
是需要的元素下标访问,和元素是
将所需的可比
。
Here the method is defined as an extension to CollectionType
becausesubscript access to the elements is needed, and the elements arerequired to be Comparable
.
这篇关于是否有可能使雨燕阵列扩展被限制在一个阶级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!