猿问

如何在Swift中扩展类型化数组?

如何使用自定义功能实用程序扩展Swift Array<T>或T[]类型?


浏览Swift的API文档可发现Array方法是的扩展T[],例如:


extension T[] : ArrayType {

    //...

    init()


    var count: Int { get }


    var capacity: Int { get }


    var isEmpty: Bool { get }


    func copy() -> T[]

}

当复制和粘贴相同的源并尝试任何变体时,例如:


extension T[] : ArrayType {

    func foo(){}

}


extension T[] {

    func foo(){}

}

它无法生成并显示以下错误:


标称类型T[]不能扩展


使用完整类型定义失败Use of undefined type 'T',即:


extension Array<T> {

    func foo(){}

}

并且也无法使用Array<T : Any>和Array<String>。


奇怪的是,Swift让我扩展了一个无类型数组:


extension Array {

    func each(fn: (Any) -> ()) {

        for i in self {

            fn(i)

        }

    }

}

它让我打电话给:


[1,2,3].each(println)

但是我无法创建适当的泛型类型扩展,因为当类型流过该方法时,该类型似乎丢失了,例如,尝试用以下方法替换Swift的内置过滤器:


extension Array {

    func find<T>(fn: (T) -> Bool) -> T[] {

        var to = T[]()

        for x in self {

            let t = x as T

            if fn(t) {

                to += t

            }

        }

        return to

    }

}

但是编译器将其视为无类型的,但仍允许使用以下命令调用扩展名:


["A","B","C"].find { $0 > "A" }

当使用调试器进行步进指示类型Swift.String为时,尝试像字符串一样访问它而不先转换为它是一个构建错误String,即:


["A","B","C"].find { ($0 as String).compare("A") > 0 }

有谁知道创建像内置扩展一样的类型化扩展方法的正确方法是什么?


斯蒂芬大帝
浏览 484回答 3
3回答

暮色呼如

对于使用类扩展类型化数组,以下内容对我有用(Swift 2.2)。例如,对类型化数组进行排序:class HighScoreEntry {&nbsp; &nbsp; let score:Int}extension Array where Element:HighScoreEntry {&nbsp; &nbsp; func sort() -> [HighScoreEntry] {&nbsp; &nbsp; &nbsp; return sort { $0.score < $1.score }&nbsp; &nbsp; }}试图做到这一点与结构或typealias会给出错误:Type 'Element' constrained to a non-protocol type 'HighScoreEntry'更新:要使用非类扩展类型化数组,请使用以下方法:typealias HighScoreEntry = (Int)extension SequenceType where Generator.Element == HighScoreEntry {&nbsp; &nbsp; func sort() -> [HighScoreEntry] {&nbsp; &nbsp; &nbsp; return sort { $0 < $1 }&nbsp; &nbsp; }}在Swift 3中,某些类型已重命名:extension Sequence where Iterator.Element == HighScoreEntry&nbsp;{&nbsp; &nbsp; // ...}

吃鸡游戏

尝试了一段时间之后,解决方案似乎<T>从签名中删除了,例如:extension Array {&nbsp; &nbsp; func find(fn: (T) -> Bool) -> [T] {&nbsp; &nbsp; &nbsp; &nbsp; var to = [T]()&nbsp; &nbsp; &nbsp; &nbsp; for x in self {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; let t = x as T;&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; if fn(t) {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; to += t&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; &nbsp; &nbsp; return to&nbsp; &nbsp; }}现在可以按预期运行,而不会出现构建错误:["A","B","C"].find { $0.compare("A") > 0 }

互换的青春

扩展所有类型:extension Array where Element: Comparable {&nbsp; &nbsp; // ...}扩展一些类型:extension Array where Element: Comparable & Hashable {&nbsp; &nbsp; // ...}扩展特定类型:extension Array where Element == Int {&nbsp; &nbsp; // ...}
随时随地看视频慕课网APP

相关分类

iOS
我要回答