Have a variable with multiple types in Swift

  • A+
Category:Languages

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

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

This variable should be able to hold only values of type Int and String.

Is this possible?

Thanks for your help ;)

 


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.

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: