Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/swift/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/wordpress/13.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Swift 在同一扩展内调用时集合扩展不可见?_Swift - Fatal编程技术网

Swift 在同一扩展内调用时集合扩展不可见?

Swift 在同一扩展内调用时集合扩展不可见?,swift,Swift,我正在收集上使用以下扩展: extension Collection where Indices.Iterator.Element == Index { subscript (safe index: Index) -> Generator.Element? { return indices.contains(index) ? self[index] : nil } } 然后我想在另一个集合扩展中的函数中使用它,如下所示: extension Colle

我正在收集上使用以下扩展:

extension Collection where Indices.Iterator.Element == Index {

    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }

}
然后我想在另一个集合扩展中的函数中使用它,如下所示:

extension Collection {

    func tesFunc() -> String? {

        let s = [safe:1]

        return nil
    }
}
我做不到这一点。我得到的错误是: “使用未解析标识符“safe”

如何在集合的第二个扩展上找到的函数中使用save下标


好问题。我最初的回答完全错了,你可以这样做

问题是您已使用
where Index.Iterator.Element==Index
约束初始
集合
扩展,但第二个扩展未受约束。您必须对这两个扩展应用相同的约束。这是正常的:

extension Collection where Indices.Iterator.Element == Index {
    subscript (safe index: Index) -> Generator.Element? {
        return indices.contains(index) ? self[index] : nil
    }
}

extension Collection where Indices.Iterator.Element == Index {
    func testFunc(index: Index) -> String? {
        let _ = self[safe: index]
        return nil
    }
}


let a = [1,2,3,4,5]

a[safe: 0] // 1
a[safe: 7] // nil
请注意,在我的
testFunc()
中,在
self[safe:index]
中使用
self
。这是必须的。否则,编译器会认为您试图创建一个键为
safe
的字典,并且无法解析
safe