Have a variable with multiple types in Swift

后端 未结 4 890
北海茫月
北海茫月 2021-01-12 03:24

I would like to have a variable, which can have multiple types (only ones, I defined), like:

var example: String, Int = 0
example = \"hi\"

4条回答
  •  太阳男子
    2021-01-12 03:46

    No, this is not possible for classes, structs, etc.

    But it is possible for protocols.

    You can this:

    protocol Walker {
    func go()
    }
    protocol Sleeper {
    func sleep()
    }
    
    var ab = Walker & Sleeper
    

    or even

        struct Person {
        var name: String
        }
    
    
    var ab = Person & Walker & Sleeper
    

    But I don't recomment use this way.

    More useful this:

    struct Person: Walker, Sleeper {
    /// code
    }
    var ab = Person
    

提交回复
热议问题