Can I simulate traits/mixins in Swift?

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

    Similar to Bryan Chen's answer:

    import Foundation
    
    protocol Named {
        var name : String { get }
    }
    
    protocol NamedExtension : Named { // NB extends Named
        var lowercaseName : String { get }
        var uppercaseName : String { get }
    }
    
    struct NamedExtensionDefault { // Put defaults inside a struct to keep name spaces seperate
        static func lowercaseName(named : NamedExtension) -> String {
            return (named.name as NSString).lowercaseString
        }
        static func uppercaseName(named : NamedExtension) -> String {
            return (named.name as NSString).uppercaseString
        }
    }
    
    extension Int : NamedExtension {
        var name : String {
        return "Int"
        }
        // Use default implementation
        var lowercaseName : String {
        return NamedExtensionDefault.lowercaseName(self)
        }
        var uppercaseName : String {
        return NamedExtensionDefault.uppercaseName(self)
        }
    }
    
    1.name // result Int
    1.uppercaseName // result "INT"
    1.lowercaseName // result "int"
    

    The main difference from Bryan's answer is that I didn't use generics because I made NamedExtension extends Named, so that the default implementations can access name.

提交回复
热议问题