Swift: Type Aliases, Booleans, Tuples
Type Aliases
Type aliases are a way to give a new name to an existing type. This can be useful for making your code more readable and understandable.
To create a type alias, use the typealias keyword. The syntax is as follows:
typealias NewTypeName = ExistingTypeNameFor example, the following code creates a type alias called
Distance for the Double type:typealias Distance = DoubleOnce you have created a type alias, you can use it anywhere you would use the existing type. For example, the following code declares a variable of type
Distance:var distance: Distance = 10.0Booleans
Booleans are a special type of value that can be eithertrue or false.Booleans are often used in conditional statements, such as
if and while statements. For example, the following code uses a boolean to control the flow of the program:let isLoggedIn = true
if isLoggedIn { // The user is logged in.} else { // The user is not logged in.}Tuples
Tuples are a way to group together values of different types.To create a tuple, use the
( and ) symbols. The syntax is as follows:(value1, value2, ...)let person = ("Alice", 25)Once you have created a tuple, you can access the individual values in the tuple using their index. For example, the following code accesses the name and age from the
person tuple:let name = person.0
let age = person.1
Tuples can also be used to return multiple values from a function. For example, the following function returns a tuple containing the sum and difference of two numbers:
func addAndSubtract(number1: Int, number2: Int) -> (Int, Int) { let sum = number1 + number2 let difference = number1 - number2 return (sum, difference) }
The following code shows how to use the
addAndSubtract() function:let result = addAndSubtract(number1: 10, number2: 5) let sum = result.0 let difference = result.1 print("The sum is \(sum).") print("The difference is \(difference).")
| Previous: Swift: Type Safety and Conversions | Next: Optionals, nil, Optional Binding |
Comments
Post a Comment