是否可以在 Swift 中创建一个仅限于一个类的数组扩展? [英] Is it possible to make an Array extension in Swift that is restricted to one class?
问题描述
我可以制作一个仅适用于字符串的数组扩展吗?
Can I make an Array extension that applies to, for instance, just Strings?
推荐答案
从 Swift 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).
一个简单的例子:为所有符合的类型定义一个方法到 SequenceType
(例如 Array
),其中序列元素是 String
:
A simple example: Define a method for all types conforming
to 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
不能直接为struct Array
定义扩展方法,只能为所有类型定义符合某些协议(带有可选约束).所以一个必须找到一个 Array
符合的协议并提供所有必要的方法.在上面的例子中,就是SequenceType
.
The extension method cannot be defined for struct Array
directly, but only for all types
conforming to some protocol (with optional constraints). So one
has to find a protocol to which Array
conforms and which provides all the necessary methods. In the above example, that is 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
.
Here the method is defined as an extension to CollectionType
because
subscript access to the elements is needed, and the elements are
required to be Comparable
.
这篇关于是否可以在 Swift 中创建一个仅限于一个类的数组扩展?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!