Details for a topic

Optionals, Tuples

Learn the syntax for Swift specific concepts like Optionals and Tuples.

All cards

What does

print(Int("18"))

print?

Optional(18)

The Int() function returns an optional Int. The String given as an argument may not represent an Int.


Test if an optional has a value or not

if anOptional != nil {
// we have a value, we can unwrap the optional
print(anOptional!)
} else {
// no value
}

Optional Binding

let optionalInt : Int?

if let myNumber = optionalInt {
    print(myNumber)
} else {
    print("no value for myNumber")
}

Tuples

Create a simple tuple without a names for the values

let myTuple = ("John", 14)

Tuples

Create a tuple with names for the values

let student = (name : "Jane", age : 18)

Tuples

Access the values of a tuple by their name

let student = (name : "Jane", age : 18)
student.name // is "Jane"
student.age // is 18 

Tuples

Access the values of a tuple without the name

let student = (name : "Jane", age : 18)
student.0 // is "Jane"
student.1 // is 18

Tuples

Decompose a tuple into variables

let student = ("Jane", 18)
let (myName, myAge) = student
// myName is "Jane"
// myAge is 185

Tuples

Tuples are used to define functions with multiple outputs.

Example:

func sinusAndCosinus(x : Double)->(sin : Double,  cos : Double) {
    return (sin(x), cos(x))
}
// sinusAndCosinus(0).sin is 0