2017-02-08 3 views
1

私はコレクションに次の拡張を使用しています:同一の内線番号内にコールされた場合、コレクション拡張は表示されませんか?

私は、このように別のコレクションの拡張で見つかった機能でそれを使用したい
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 
    } 
} 

私はこの仕事をすることはできませんよ。私が手にエラーがある:?未解決識別子の 「使用 『安全』

コレクションの第二延長上にある機能で保存するの添え字を使用することができますどのように

Error as shown in a Playground

答えて

1

グレート質問私の最初の。答えは完全に間違っていたとあなたはこれを行うことができます。

問題は、あなたがwhere Indices.Iterator.Element == Indexと初期Collection拡張子を制約しましたが、第2の拡張が制約されていないということです。あなたは肝炎e両方に同じ制約を適用する。これはokです:self[safe: index]selfの私testFunc()使用中

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 

注意。それは必須です。そうでなければ、コンパイラは、safeのキーで辞書を作成しようとしていると判断し、safeを解決できません。

関連する問題