Is it possible to make an Array extension in Swift that is restricted to one class?

后端 未结 4 776
暖寄归人
暖寄归人 2020-11-27 21:39

Can I make an Array extension that applies to, for instance, just Strings?

4条回答
  •  醉酒成梦
    2020-11-27 21:40

    This has already been answered by the three wise-men above ;-) , but I humbly offer a generalization of @Martin's answer. We can target an arbitrary class by using "marker" protocol that is only implemented on the class that we wish to target. Ie. one does not have to find a protocol per-se, but can create a trivial one for using in targeting the desired class.

    protocol TargetType {}
    extension Array:TargetType {}
    
    struct Foo  {
        var name:String
    }
    
    extension CollectionType where Self:TargetType, Generator.Element == Foo {
        func byName() -> [Foo] { return sort { l, r in l.name < r.name } }
    }
    
    let foos:[Foo] = ["c", "b", "a"].map { s in Foo(name: s) }
    print(foos.byName())
    

提交回复
热议问题