Have a variable with multiple types in Swift

后端 未结 4 921
北海茫月
北海茫月 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:44

    Here is how you can achieve it. Works exactly how you'd expect.

    protocol StringOrInt { }
    
    extension Int: StringOrInt { }
    extension String: StringOrInt { }
    
    var a: StringOrInt = "10"
    a = 10 //> 10
    a = "q" //> "q"
    a = 0.8 //> Error
    

    NB! I would not suggest you to use it in production code. It might be confusing for your teammates.

    UPD: as @Martin R mentioned: Note that this restricts the possible types only “by convention.” Any module (or source file) can add a extension MyType: StringOrInt { } conformance.

提交回复
热议问题