Swift – Get Type of Variable
To get type of a variable in Swift, call type(of:)
function, and pass the variable as argument for of:
parameter.
Example
In the following example, we will initialise a variable with the value 3.28
, and programmatically get the type of this variable.
main.swift
</>
Copy
import Foundation
var x = 3.28
print(type(of: x))
Output
Double
Now, let us initialize the variable with “Hello World”, and get the type of this variable. We know that this variable is of type String. Let us check that programmatically.
main.swift
</>
Copy
import Foundation
var x = "Hello World"
print(type(of: x))
Output
String
Similarly, we can get type of any variable using type(of:)
function.
Conclusion
In this Swift Tutorial, we learned how to get the type of a variable in Swift using type(of:) function, with the help of example.