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