Can I simulate traits/mixins in Swift?

前端 未结 5 652
南旧
南旧 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:26

    One way to simulate mixing is use generic function to provide implementation

    For example with these protocols

    protocol Named {
        func GetName() -> String
    }
    
    protocol NamedExtension {
        func GetLowercaseName() -> String
        func GetUppercaseName() -> String
    }
    

    I want some class to implement GetName() and use mixing so they also get GetLowercaseName() and GetUppercaseName() without implement them

    This is the implementation of NamedExtension as in free function

    func GetLowercaseNameImpl(obj:T) -> String {
        return obj.GetName().lowercaseString
    }
    
    func GetUppercaseNameImpl(obj:T) -> String {
        return obj.GetName().uppercaseString
    }
    

    and extensions on Int

    extension Int : Named {
        func GetName() -> String {
            return "Int"
        }
    }
    
    extension Int : NamedExtension {
        // use provided implementation
        func GetLowercaseName() -> String {
            return GetLowercaseNameImpl(self)
        }
        func GetUppercaseName() -> String {
            return GetUppercaseNameImpl(self)
        }
    }
    

    and I can use

    1.GetName() // result Int
    1.GetUppercaseName() // result "INT"
    1.GetLowercaseName() // result "int"
    

提交回复
热议问题