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 ;)
You can declare multiple constants or multiple variables on a single line, separated by commas: var x = 0.0, y = 0.0, z = 0.0.
Swift Double Like Float , a double data type is also used to represent a number with fractional components. However, Double supports data up to 15 decimal places. We use the Double keyword to create double variables.
To get type of a variable in Swift, call type(of:) function, and pass the variable as argument for of: parameter.
For example, Here, Int is a data type that specifies that the num variable can only store integer data. There are six basic types of data types in Swift programming. "hello world!" The character data type is used to represent a single-character string. We use the Character keyword to create character-type variables. For example,
Swift - Variables. A variable provides us with named storage that our programs can manipulate. Each variable in Swift 4 has a specific type, which determines the size and layout of the variable's memory; the range of values that can be stored within that memory; and the set of operations that can be applied to the variable.
As with Int and Double above, you don’t need to declare constants or variables as Bool if you set them to true or false as soon as you create them. Type inference helps make Swift code more concise and readable when it initializes constants or variables with other values whose type is already known.
Here are some of the basic properties of integers in swift programming. Swift programming provides different variants of Int type having different sizes. A boolean data type is used to represent logical entities. It can have one of two values: true or false. We use the Bool keyword to create boolean-type variables. For example,
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With