Type Aliases
Type aliases
define an alternative name for an existing type. You define type aliases with the typealias keyword.
Type aliases are useful when you want to refer to an existing type by a name that is contextually more appropriate, such as when working with data of a specific size from an external source:
typealias AudioSample = UInt16
Once you define a type alias, you can use the alias anywhere you might use the original name:
1 v ar maxAmplitudeFound = AudioSample.min
2 // maxAmplitudeFound is now 0
Here, AudioSample is defined as an alias for UInt16. Because it is an alias, the call to AudioSample.min actually calls UInt16.min, which provides an initial value of 0 for the maxAmplitudeFound variable.
Booleans
Swift has a basic
Boolean
type, called Bool. Boolean values are referred to as
logical
, because they can only ever be true or false. Swift provides two Boolean constant values, true and false:
1 let orangesAreOrange = true
2 let turnipsAreDelicious = false
The types of orangesAreO range and turnipsAreDelicious have been inferred as Bool from the fact that they were initialized with Boolean literal values. 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.
Boolean values are particularly useful when you work with conditional statements such as the if statement:
1 if turnipsAreDelicious {
2 println("Mmm, tasty turnips!")
3 } else {
4 println("Eww, turnips are horrible.")
5 }
6 // prints "Eww, turnips are horrible."
Conditional statements such as the if statement are covered in more detail in Control Flow.
Swift’s type safety prevents non-Boolean values from being be substituted for Bool. The following example reports a compile-time error:
1 let i = 1
2 if i {
3 // this example will not compile, and will report an error
4 }
However, the alternative example below is valid:
1 let i = 1
2 if i == 1 {
3 // this example will compile successfully
4 }
The result of the i == 1 comparison is of type Bool, and so this second example passes the type-check. Comparisons like i == 1 are discussed in Basic Operators.
As with other examples of type safety in Swift, this approach avoids accidental errors and ensures that the intention of a particular section of code is always clear.
Tuples
Tuples
group multiple values into a single compound value. The values within a tuple can be of any type and do not have to be of the same type as each other.
In this example, (404, "Not Found") is a tuple that describes an
HTTP status code
. An HTTP status code is a special value returned by a web server whenever you request a web page. A status code of 404 Not Found is returned if you request a
webpage that doesn’t exist.
1 let http404Error = (404, "Not Found")
2 // http404Error is of type (Int, String), and equals (404, "Not Found")
The (404, "Not Found") tuple groups together an Int and a String to give the HTTP status code two separate values: a number and a human-readable description. It can be described as “a tuple of type (Int, String)”.
You can create tuples from any permutation of types, and they can contain as many different types as you like. There’s nothing stopping you from having a tuple of type (Int, Int, Int), or (String, Bool), or indeed any other permutation you require.
You can
decompose
a tuple’s contents into separate constants or variables, which you then access as usual:
1 let (statusCode, statusMessage) = http404Error
2 println("The status code is \(statusCode)")
3 // prints "The status code is 404"
4 println("The status message is \(statusMessage)")
5 // prints "The status message is Not Found"
If you only need some of the tuple’s values, ignore parts of the tuple with an underscore (_) when you decompose the tuple:
1 let (justTheStatusCode, _) = http404Error
2 println("The status code is \(justTheStatusCode)")
3 // prints "The status code is 404"
Alternatively, access the individual element values in a tuple using index numbers starting at zero:
1 println("The status code is \(http404Error.0)")
2 // prints "The status code is 404"
3 println("The status message is \(http404Error.1)")
4 // prints "The status message is Not Found"
You can name the individual elements in a tuple when the tuple is defined:
let http200Status = (statusCode: 200, description: "O K")
If you name the elements in a tuple, you can use the element names to access the values of those elements: