Can I simulate traits/mixins in Swift?

前端 未结 5 646
南旧
南旧 2021-02-01 16:45

Does Swift have a way of mixing in traits, a la Scala? The section of the Swift book on using extensions to add protocols to existing classes comes tantalizingly close. However,

5条回答
  •  走了就别回头了
    2021-02-01 17:23

    I don't know Scala, but from what you're telling me it is possible to simultaneously create a protocol and an extension that extends a type to add "pseudo-trait" behavior.

    For example:

    protocol IsGreaterThan
    {
        func isGreaterThan(other:Int) -> Bool
        func isNotGreaterThan(other:Int) -> Bool
    }
    
    extension Int : IsGreaterThan
    {
        func isGreaterThan(other:Int) -> Bool
        {
            return self > other
        }
    
        func isNotGreaterThan(other:Int) -> Bool
        {
            return !isGreaterThan(other)
        }
    }
    

    The real hamstring is how generics are somewhat limited for now. I think they will improve a lot in the coming revisions of Swift.

提交回复
热议问题