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 ;)
An “enumeration with associated value” might be what you are looking for:
You can either assign a string or an integer:
Retrieving the contents is done with a switch-statement:
If you declare conformance to the
Equatable
protocol then you can also check values for equality:No, this is not possible for classes, structs, etc.
But it is possible for protocols.
You can this:
or even
But I don't recomment use this way.
More useful this:
Here is how you can achieve it. Works exactly how you'd expect.
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.You can use
Tuple
.Example:
And access each data by index: