是否有可能使雨燕阵列扩展被限制在一个阶级? [英] Is it possible to make an Array extension in Swift that is restricted to one class?

查看:142
本文介绍了是否有可能使雨燕阵列扩展被限制在一个阶级?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以适用于,例如数组延伸,只是字符串?

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 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

扩展方法不能用于结构数组定义直接,但仅限于所有类型
符合某种协议(带有可选的约束)。所以一
必须找到哪个阵列符合并提供所有必要的方法的协议。在上面的例子中,即序列类型

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.

另一个例子(的<一个变化href=\"http://stackoverflow.com/questions/26678362/how-do-i-insert-an-element-at-the-correct-position-into-a-sorted-array-in-swift\">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

下面的方法被定义为一个扩展 Col​​lectionType ,因为
是需要的元素下标访问,和元素是
将所需的可比

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.

这篇关于是否有可能使雨燕阵列扩展被限制在一个阶级?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆