Swift's type system
Swift is a strongly typed language, which means that every constant and variable is defined with a specific type. Only values of a matching type can be assigned to them. So far, we have been taking advantage of a feature of Swift called type inference. This makes it such that the code does not have to explicitly declare a type if it can be inferred from the value assigned to it during declaration.
Without the type inference, the name variable declaration from before would be written as:
var name: String = "Sarah"
This code explicitly declares name
as the type String
with the value "Sarah"
. A constant or variable's type can be specified by adding a colon (:
) and a type after its name.
A String
type is defined by a series of characters. This is perfect for storing text like our name example. The reason that we don't actually need to specify the type is that "Sarah"
is a String
literal. The text surrounded by quotation marks is a String
literal and is inferred to be of the type...