Swift Data Types
A data type is the kind of a stored value.
Naming the kind of each value
type(of:) names the kind of a value, and each stored value has a kind. The four printed lines name the kinds in the same order as the values above them.
var whole = 4
var price = 2.5
var word = "cup"
var ready = true
print(type(of: whole))
print(type(of: price))
print(type(of: word))
print(type(of: ready))Writing types beside names
The score line carries an Int annotation beside its name. The label line carries a String annotation beside its name.
var score: Int = 12
var label: String = "Points"
print(label, score)A kind picked from the value
No annotation sits beside count in this code. The printed kind is Int, taken from the value 8.
var count = 8
print(type(of: count))A mismatched annotation fails
The annotation asks for a String and the value is a number. The compiler stops at that mismatch.
let name: String = 42Example
var age: Int = 20
var height = 1.8
var city: String = "York"
var member = true
print(city, age)
print(type(of: height))
print(member)Key points
- Int: a whole number type.
- Double: a number type with a decimal part.
- String: a text type.
- Bool: a type with the two values true and false.
- A type annotation writes the type after a colon beside the name.
- Type inference picks a type from the value first given to a name.
In this example, age gets the annotation Int and the value 20. Height gets 1.8 with no annotation. City gets the annotation String and the value York. Member gets the value true with no annotation. The first print shows York and 20 on one line. The next print names the kind of height as Double. The last print shows true.
Try it Yourself
Edit the code, then press Run.
Running is simulated ยท Programiz Swift Compiler
Exercise
Which type holds the values true and false?