greet(person:)
String person String
1 func greet(person: String) -> String {
2 let greeting = "Hello, " + person + "!"
3 return greeting
4 }
func
->
ON THIS PAGE
1 print(greet(person: "Anna"))
2 // Prints "Hello, Anna!"
3 print(greet(person: "Brian"))
4 // Prints "Hello, Brian!"
greet(person:) String person
greet(person: "Anna") String greet(person:)
print(_:separator:terminator:)
print(_:separator:terminator:)
greet(person:) String greeting
return return greeting
greeting
greet(person:)
"Anna" "Brian"
1 func greetAgain(person: String) -> String {
2 return "Hello again, " + person + "!"
3 }
4 print(greetAgain(person: "Anna"))
5 // Prints "Hello again, Anna!"
String
1 func sayHelloWorld() -> String {
ON THIS PAGE
2 return "hello, world"
3 }
4 print(sayHelloWorld())
5 // Prints "hello, world"
1 func greet(person: String, alreadyGreeted: Bool) -> String {
2 if alreadyGreeted {
3 return greetAgain(person: person)
4 } else {
5 return greet(person: person)
6 }
7 }
8 print(greet(person: "Tim", alreadyGreeted: true))
9 // Prints "Hello again, Tim!"
greet(person:alreadyGreeted:) String
person Bool alreadyGreeted
greet(person:)
greet
greet(person:alreadyGreeted:) greet(person:)
greet(person:)
String
1 func greet(person: String) {
2 print("Hello, (person)!")
3 }
4 greet(person: "Dave")
5 // Prints "Hello, Dave!"
ON THIS PAGE
->
greet(person:)
Void
()
1 func printAndCount(string: String) -> Int {
2 print(string)
3 return string.count
4 }
5 func printWithoutCounting(string: String) {
6 let _ = printAndCount(string: string)
7 }
8 printAndCount(string: "hello, world")
9 // prints "hello, world" and returns a value of 12
10 printWithoutCounting(string: "hello, world")
11 // prints "hello, world" but does not return a value
printAndCount(string:)
Int printWithoutCounting(string:)
minMax(array:)
Int
1 func minMax(array: [Int]) -> (min: Int, max: Int) {
2 var currentMin = array[0]
3 var currentMax = array[0]
4 for value in array[1..<array.count] {
5 if value < currentMin {
6 currentMin = value
7 } else if value > currentMax {
ON THIS PAGE
8 currentMax = value
9 }
10 }
11 return (currentMin, currentMax)
12 }
minMax(array:) Int
min max
minMax(array:) currentMin
currentMax
currentMin currentMax
Int
1 let bounds = minMax(array: [8, -6, 2, 109, 3, 71])
2 print("min is (bounds.min) and max is (bounds.max)")
3 // Prints "min is -6 and max is 109"
nil
(Int, Int)? (String, Int, Bool)?
(Int, Int)?
(Int?, Int?)
minMax(array:) Int
array
minMax(array:)
array[0]
minMax(array:)
nil
1 func minMax(array: [Int]) -> (min: Int, max: Int)? {
2 if array.isEmpty { return nil }
ON THIS PAGE
3 var currentMin = array[0]
4 var currentMax = array[0]
5 for value in array[1..<array.count] {
6 if value < currentMin {
7 currentMin = value
8 } else if value > currentMax {
9 currentMax = value
10 }
11 }
12 return (currentMin, currentMax)
13 }
minMax(array:)
nil
1 if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) {
2 print("min is (bounds.min) and max is (bounds.max)")
3 }
4 // Prints "min is -6 and max is 109"
1 func greeting(for person: String) -> String {
2 "Hello, " + person + "!"
3 }
4 print(greeting(for: "Dave"))
5 // Prints "Hello, Dave!"
6
7 func anotherGreeting(for person: String) -> String {
8 return "Hello, " + person + "!"
9 }
10 print(anotherGreeting(for: "Dave"))
11 // Prints "Hello, Dave!"
greeting(for:)
anotherGreeting(for:)
return
return return
ON THIS PAGE
1 func someFunction(firstParameterName: Int, secondParameterName: Int) {
2 // In the function body, firstParameterName and secondParameterName
3 // refer to the argument values for the first and second parameters.
4 }
5 someFunction(firstParameterName: 1, secondParameterName: 2)
1 func someFunction(argumentLabel parameterName: Int) {
2 // In the function body, parameterName refers to the argument value
3 // for that parameter.
4 }
greet(person:)
1 func greet(person: String, from hometown: String) -> String {
2 return "Hello (person)! Glad you could visit from (hometown)."
3 }
4 print(greet(person: "Bill", from: "Cupertino"))
5 // Prints "Hello Bill! Glad you could visit from Cupertino."
_
1 func someFunction(_ firstParameterName: Int, secondParameterName: Int) {
2 // In the function body, firstParameterName and secondParameterName
3 // refer to the argument values for the first and second parameters.
4 }
5 someFunction(1, secondParameterName: 2)
ON THIS PAGE
1 func someFunction(parameterWithoutDefault: Int, parameterWithDefault: Int
= 12) {
2 // If you omit the second argument when calling this function, then
3 // the value of parameterWithDefault is 12 inside the function body.
4 }
5 someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) //
parameterWithDefault is 6
6 someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12
...
numbers
Double... numbers
[Double]
1 func arithmeticMean(_ numbers: Double...) -> Double {
2 var total: Double = 0
3 for number in numbers {
4 total += number
5 }
6 return total / Double(numbers.count)
7 }
8 arithmeticMean(1, 2, 3, 4, 5)
9 // returns 3.0, which is the arithmetic mean of these five numbers
10 arithmeticMean(3, 8.25, 18.75)
11 // returns 10.0, which is the arithmetic mean of these three numbers
ON THIS PAGE
inout
&
inout
swapTwoInts(_:_:)
a b
1 func swapTwoInts(_ a: inout Int, _ b: inout Int) {
2 let temporaryA = a
3 a = b
4 b = temporaryA
5 }
swapTwoInts(_:_:) b a a b
a temporaryA
b a temporaryA b
swapTwoInts(_:_:) Int
someInt anotherInt
swapTwoInts(_:_:)
1 var someInt = 3
2 var anotherInt = 107
3 swapTwoInts(&someInt, &anotherInt)
4 print("someInt is now (someInt), and anotherInt is now (anotherInt)")
5 // Prints "someInt is now 107, and anotherInt is now 3"
ON THIS PAGE
someInt anotherInt
swapTwoInts(_:_:)
swapTwoInts
someInt anotherInt
1 func addTwoInts(_ a: Int, _ b: Int) -> Int {
2 return a + b
3 }
4 func multiplyTwoInts(_ a: Int, _ b: Int) -> Int {
5 return a * b
6 }
addTwoInts multiplyTwoInts
Int Int
(Int, Int) -> Int
Int Int
1 func printHelloWorld() {
2 print("hello, world")
3 }
() -> Void Void
var mathFunction: (Int, Int) -> Int = addTwoInts
ON THIS PAGE
mathFunction Int
Int addTwoInts
addTwoInts(_:_:) mathFunction
mathFunction
1 print("Result: (mathFunction(2, 3))")
2 // Prints "Result: 5"
1 mathFunction = multiplyTwoInts
2 print("Result: (mathFunction(2, 3))")
3 // Prints "Result: 6"
1 let anotherMathFunction = addTwoInts
2 // anotherMathFunction is inferred to be of type (Int, Int) -> Int
(Int, Int) -> Int
1 func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b:
Int) {
2 print("Result: (mathFunction(a, b))")
3 }
4 printMathResult(addTwoInts, 3, 5)
5 // Prints "Result: 8"
printMathResult(_:_:_:)
mathFunction (Int, Int) -> Int
a
b Int
ON THIS PAGE
printMathResult(_:_:_:) addTwoInts(_:_:)
3 5 3 5 8
printMathResult(_:_:_:)
printMathResult(_:_:_:)
->
stepForward(_:) stepBackward(_:)
stepForward(_:) stepBackward(_:)
(Int) -> Int
1 func stepForward(_ input: Int) -> Int {
2 return input + 1
3 }
4 func stepBackward(_ input: Int) -> Int {
5 return input - 1
6 }
chooseStepFunction(backward:) (Int) -> Int
chooseStepFunction(backward:) stepForward(_:)
stepBackward(_:) backward
1 func chooseStepFunction(backward: Bool) -> (Int) -> Int {
2 return backward ? stepBackward : stepForward
3 }
chooseStepFunction(backward:)
1 var currentValue = 3
2 let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
3 // moveNearerToZero now refers to the stepBackward() function
currentValue currentValue 3
currentValue > 0 true chooseStepFunction(backward:)
stepBackward(_:)
moveNearerToZero
moveNearerToZero
ON THIS PAGE
1 print("Counting to zero:")
2 // Counting to zero:
3 while currentValue != 0 {
4 print("(currentValue)... ")
5 currentValue = moveNearerToZero(currentValue)
6 }
7 print("zero!")
8 // 3...
9 // 2...
10 // 1...
11 // zero!
chooseStepFunction(backward:)
1 func chooseStepFunction(backward: Bool) -> (Int) -> Int {
2 func stepForward(input: Int) -> Int { return input + 1 }
3 func stepBackward(input: Int) -> Int { return input - 1 }
4 return backward ? stepBackward : stepForward
5 }
6 var currentValue = -4
7 let moveNearerToZero = chooseStepFunction(backward: currentValue > 0)
8 // moveNearerToZero now refers to the nested stepForward() function
9 while currentValue != 0 {
10 print("(currentValue)... ")
11 currentValue = moveNearerToZero(currentValue)
12 }
13 print("zero!")
14 // -4...
15 // -3...
16 // -2...
17 // -1...
18 // zero!
ON THIS PAGE
ON THIS PAGE
ON THIS PAGE
sorted(by:)
sorted(by:)
sorted(by:)
sorted(by:)
sorted(by:)
String
let names = ["Chris", "Alex", "Ewa", "Barry", "Daniella"]
sorted(by:)
Bool
true false
String
(String, String) -> Bool
sorted(by:)
1 func backward(_ s1: String, _ s2: String) -> Bool {
2 return s1 > s2
3 }
4 var reversedNames = names.sorted(by: backward)
5 // reversedNames is equal to ["Ewa", "Daniella", "Chris",
"Barry", "Alex"]
ON THIS PAGE
s1 s2 backward(_:_:)
true s1 s2
"B" "A" "Tom"
"Tim" "Barry"
"Alex"
a > b
{ ( parameters ) -> return type in
statements
}
backward(_:_:)
1 reversedNames = names.sorted(by: { (s1: String, s2: String) ->
Bool in
2 return s1 > s2
3 })
backward(_:_:)
(s1: String, s2: String) -> Bool
in
ON THIS PAGE
reversedNames = names.sorted(by: { (s1: String, s2: String) ->
Bool in return s1 > s2 } )
sorted(by:)
sorted(by:)
(String, String) -> Bool (String, String) Bool
->
reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } )
sorted(by:)
String
return
reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } )
ON THIS PAGE
sorted(by:) Bool
s1 > s2 Bool return
$0 $1 $2
in
reversedNames = names.sorted(by: { $0 > $1 } )
$0 $1 String
String
>
String Bool
sorted(by:)
reversedNames = names.sorted(by: >)
ON THIS PAGE
1 func someFunctionThatTakesAClosure(closure: () -> Void) {
2 // function body goes here
3 }
4
5 // Here's how you call this function without using a trailing
closure:
6
7 someFunctionThatTakesAClosure(closure: {
8 // closure's body goes here
9 })
10
11 // Here's how you call this function with a trailing closure
instead:
12
13 someFunctionThatTakesAClosure() {
14 // trailing closure's body goes here
15 }
sorted(by:)
reversedNames = names.sorted() { $0 > $1 }
()
reversedNames = names.sorted { $0 > $1 }
Array map(_:)
map(_:)
ON THIS PAGE
map(_:)
Int String [16, 58, 510]
["OneSix", "FiveEight", "FiveOneZero"]
1 let digitNames = [
2 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four",
3 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine"
4 ]
5 let numbers = [16, 58, 510]
numbers String
map(_:)
1 let strings = numbers.map { (number) -> String in
2 var number = number
3 var output = ""
4 repeat {
5 output = digitNames[number % 10]! + output
6 number /= 10
7 } while number > 0
8 return output
9 }
10 // strings is inferred to be of type [String]
11 // its value is ["OneSix", "FiveEight", "FiveOneZero"]
map(_:)
number
number number
String
output
number number % 10
digitNames
ON THIS PAGE
digitNames !
number % 10
digitNames
String
digitNames output
number % 10 6 16 8 58 0 510
number 10
16 1 58 5 510 51
number 0 output
map(_:)
map(_:)
makeIncrementer
incrementer incrementer()
runningTotal amount
incrementer makeIncrementer runningTotal
amount
1 func makeIncrementer(forIncrement amount: Int) -> () -> Int {
2 var runningTotal = 0
3 func incrementer() -> Int {
ON THIS PAGE
4 runningTotal += amount
5 return runningTotal
6 }
7 return incrementer
8 }
makeIncrementer () -> Int
Int
makeIncrementer(forIncrement:)
runningTotal
0
makeIncrementer(forIncrement:) Int
forIncrement amount
runningTotal
makeIncrementer
incrementer
amount runningTotal
incrementer()
1 func incrementer() -> Int {
2 runningTotal += amount
3 return runningTotal
4 }
incrementer()
runningTotal amount
runningTotal amount
runningTotal
amount makeIncrementer
runningTotal incrementer
ON THIS PAGE
makeIncrementer
let incrementByTen = makeIncrementer(forIncrement: 10)
incrementByTen
10 runningTotal
1 incrementByTen()
2 // returns a value of 10
3 incrementByTen()
4 // returns a value of 20
5 incrementByTen()
6 // returns a value of 30
runningTotal
1 let incrementBySeven = makeIncrementer(forIncrement: 7)
2 incrementBySeven()
3 // returns a value of 7
incrementByTen
runningTotal incrementBySeven
1 incrementByTen()
2 // returns a value of 40
incrementBySeven incrementByTen
runningTotal
ON THIS PAGE
incrementByTen
1 let alsoIncrementByTen = incrementByTen
2 alsoIncrementByTen()
3 // returns a value of 50
4
5 incrementByTen()
6 // returns a value of 60
alsoIncrementByTen
incrementByTen
@escaping
1 var completionHandlers: [() -> Void] = []
2 func someFunctionWithEscapingClosure(completionHandler: @escaping
() -> Void) {
3 completionHandlers.append(completionHandler)
4 }
someFunctionWithEscapingClosure(_:)
@escaping
ON THIS PAGE
@escaping self
someFunctionWithEscapingClosure(_:)
self
someFunctionWithNonescapingClosure(_:)
self
1 func someFunctionWithNonescapingClosure(closure: () -> Void) {
2 closure()
3 }
4
5 class SomeClass {
6 var x = 10
7 func doSomething() {
8 someFunctionWithEscapingClosure { self.x = 100 }
9 someFunctionWithNonescapingClosure { x = 200 }
10 }
11 }
12
13 let instance = SomeClass()
14 instance.doSomething()
15 print(instance.x)
16 // Prints "200"
17
18 completionHandlers.first?()
19 print(instance.x)
20 // Prints "100"
ON THIS PAGE
assert(condition:message:file:line:)
condition message condition
message
condition false
1 var customersInLine = ["Chris", "Alex", "Ewa", "Barry",
"Daniella"]
2 print(customersInLine.count)
3 // Prints "5"
4
5 let customerProvider = { customersInLine.remove(at: 0) }
6 print(customersInLine.count)
7 // Prints "5"
8
9 print("Now serving (customerProvider())!")
10 // Prints "Now serving Chris!"
11 print(customersInLine.count)
12 // Prints "4"
customersInLine
customerProvider
String () -> String
1 // customersInLine is ["Alex", "Ewa", "Barry", "Daniella"]
2 func serve(customer customerProvider: () -> String) {
3 print("Now serving (customerProvider())!")
4 }
5 serve(customer: { customersInLine.remove(at: 0) } )
6 // Prints "Now serving Alex!"
ON THIS PAGE
serve(customer:)
serve(customer:)
@autoclosure
String
customerProvider
@autoclosure
1 // customersInLine is ["Ewa", "Barry", "Daniella"]
2 func serve(customer customerProvider: @autoclosure () -> String)
{
3 print("Now serving (customerProvider())!")
4 }
5 serve(customer: customersInLine.remove(at: 0))
6 // Prints "Now serving Ewa!"
@autoclosure
@escaping @escaping
1 // customersInLine is ["Barry", "Daniella"]
2 var customerProviders: [() -> String] = []
3 func collectCustomerProviders(_ customerProvider: @autoclosure
@escaping () -> String) {
4 customerProviders.append(customerProvider)
5 }
6 collectCustomerProviders(customersInLine.remove(at: 0))
7 collectCustomerProviders(customersInLine.remove(at: 0))
8
9 print("Collected (customerProviders.count) closures.")
10 // Prints "Collected 2 closures."
11 for customerProvider in customerProviders {
12 print("Now serving (customerProvider())!")
13 }
14 // Prints "Now serving Barry!"
15 // Prints "Now serving Daniella!"
ON THIS PAGE
customerProvider
collectCustomerProviders(_:)
customerProviders
customerProvider
ON THIS PAGE

Swift 5.1 Language Guide Notes.pdf

  • 1.
    greet(person:) String person String 1func greet(person: String) -> String { 2 let greeting = "Hello, " + person + "!" 3 return greeting 4 } func -> ON THIS PAGE
  • 2.
    1 print(greet(person: "Anna")) 2// Prints "Hello, Anna!" 3 print(greet(person: "Brian")) 4 // Prints "Hello, Brian!" greet(person:) String person greet(person: "Anna") String greet(person:) print(_:separator:terminator:) print(_:separator:terminator:) greet(person:) String greeting return return greeting greeting greet(person:) "Anna" "Brian" 1 func greetAgain(person: String) -> String { 2 return "Hello again, " + person + "!" 3 } 4 print(greetAgain(person: "Anna")) 5 // Prints "Hello again, Anna!" String 1 func sayHelloWorld() -> String { ON THIS PAGE
  • 3.
    2 return "hello,world" 3 } 4 print(sayHelloWorld()) 5 // Prints "hello, world" 1 func greet(person: String, alreadyGreeted: Bool) -> String { 2 if alreadyGreeted { 3 return greetAgain(person: person) 4 } else { 5 return greet(person: person) 6 } 7 } 8 print(greet(person: "Tim", alreadyGreeted: true)) 9 // Prints "Hello again, Tim!" greet(person:alreadyGreeted:) String person Bool alreadyGreeted greet(person:) greet greet(person:alreadyGreeted:) greet(person:) greet(person:) String 1 func greet(person: String) { 2 print("Hello, (person)!") 3 } 4 greet(person: "Dave") 5 // Prints "Hello, Dave!" ON THIS PAGE
  • 4.
    -> greet(person:) Void () 1 func printAndCount(string:String) -> Int { 2 print(string) 3 return string.count 4 } 5 func printWithoutCounting(string: String) { 6 let _ = printAndCount(string: string) 7 } 8 printAndCount(string: "hello, world") 9 // prints "hello, world" and returns a value of 12 10 printWithoutCounting(string: "hello, world") 11 // prints "hello, world" but does not return a value printAndCount(string:) Int printWithoutCounting(string:) minMax(array:) Int 1 func minMax(array: [Int]) -> (min: Int, max: Int) { 2 var currentMin = array[0] 3 var currentMax = array[0] 4 for value in array[1..<array.count] { 5 if value < currentMin { 6 currentMin = value 7 } else if value > currentMax { ON THIS PAGE
  • 5.
    8 currentMax =value 9 } 10 } 11 return (currentMin, currentMax) 12 } minMax(array:) Int min max minMax(array:) currentMin currentMax currentMin currentMax Int 1 let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) 2 print("min is (bounds.min) and max is (bounds.max)") 3 // Prints "min is -6 and max is 109" nil (Int, Int)? (String, Int, Bool)? (Int, Int)? (Int?, Int?) minMax(array:) Int array minMax(array:) array[0] minMax(array:) nil 1 func minMax(array: [Int]) -> (min: Int, max: Int)? { 2 if array.isEmpty { return nil } ON THIS PAGE
  • 6.
    3 var currentMin= array[0] 4 var currentMax = array[0] 5 for value in array[1..<array.count] { 6 if value < currentMin { 7 currentMin = value 8 } else if value > currentMax { 9 currentMax = value 10 } 11 } 12 return (currentMin, currentMax) 13 } minMax(array:) nil 1 if let bounds = minMax(array: [8, -6, 2, 109, 3, 71]) { 2 print("min is (bounds.min) and max is (bounds.max)") 3 } 4 // Prints "min is -6 and max is 109" 1 func greeting(for person: String) -> String { 2 "Hello, " + person + "!" 3 } 4 print(greeting(for: "Dave")) 5 // Prints "Hello, Dave!" 6 7 func anotherGreeting(for person: String) -> String { 8 return "Hello, " + person + "!" 9 } 10 print(anotherGreeting(for: "Dave")) 11 // Prints "Hello, Dave!" greeting(for:) anotherGreeting(for:) return return return ON THIS PAGE
  • 7.
    1 func someFunction(firstParameterName:Int, secondParameterName: Int) { 2 // In the function body, firstParameterName and secondParameterName 3 // refer to the argument values for the first and second parameters. 4 } 5 someFunction(firstParameterName: 1, secondParameterName: 2) 1 func someFunction(argumentLabel parameterName: Int) { 2 // In the function body, parameterName refers to the argument value 3 // for that parameter. 4 } greet(person:) 1 func greet(person: String, from hometown: String) -> String { 2 return "Hello (person)! Glad you could visit from (hometown)." 3 } 4 print(greet(person: "Bill", from: "Cupertino")) 5 // Prints "Hello Bill! Glad you could visit from Cupertino." _ 1 func someFunction(_ firstParameterName: Int, secondParameterName: Int) { 2 // In the function body, firstParameterName and secondParameterName 3 // refer to the argument values for the first and second parameters. 4 } 5 someFunction(1, secondParameterName: 2) ON THIS PAGE
  • 8.
    1 func someFunction(parameterWithoutDefault:Int, parameterWithDefault: Int = 12) { 2 // If you omit the second argument when calling this function, then 3 // the value of parameterWithDefault is 12 inside the function body. 4 } 5 someFunction(parameterWithoutDefault: 3, parameterWithDefault: 6) // parameterWithDefault is 6 6 someFunction(parameterWithoutDefault: 4) // parameterWithDefault is 12 ... numbers Double... numbers [Double] 1 func arithmeticMean(_ numbers: Double...) -> Double { 2 var total: Double = 0 3 for number in numbers { 4 total += number 5 } 6 return total / Double(numbers.count) 7 } 8 arithmeticMean(1, 2, 3, 4, 5) 9 // returns 3.0, which is the arithmetic mean of these five numbers 10 arithmeticMean(3, 8.25, 18.75) 11 // returns 10.0, which is the arithmetic mean of these three numbers ON THIS PAGE
  • 9.
    inout & inout swapTwoInts(_:_:) a b 1 funcswapTwoInts(_ a: inout Int, _ b: inout Int) { 2 let temporaryA = a 3 a = b 4 b = temporaryA 5 } swapTwoInts(_:_:) b a a b a temporaryA b a temporaryA b swapTwoInts(_:_:) Int someInt anotherInt swapTwoInts(_:_:) 1 var someInt = 3 2 var anotherInt = 107 3 swapTwoInts(&someInt, &anotherInt) 4 print("someInt is now (someInt), and anotherInt is now (anotherInt)") 5 // Prints "someInt is now 107, and anotherInt is now 3" ON THIS PAGE
  • 10.
    someInt anotherInt swapTwoInts(_:_:) swapTwoInts someInt anotherInt 1func addTwoInts(_ a: Int, _ b: Int) -> Int { 2 return a + b 3 } 4 func multiplyTwoInts(_ a: Int, _ b: Int) -> Int { 5 return a * b 6 } addTwoInts multiplyTwoInts Int Int (Int, Int) -> Int Int Int 1 func printHelloWorld() { 2 print("hello, world") 3 } () -> Void Void var mathFunction: (Int, Int) -> Int = addTwoInts ON THIS PAGE
  • 11.
    mathFunction Int Int addTwoInts addTwoInts(_:_:)mathFunction mathFunction 1 print("Result: (mathFunction(2, 3))") 2 // Prints "Result: 5" 1 mathFunction = multiplyTwoInts 2 print("Result: (mathFunction(2, 3))") 3 // Prints "Result: 6" 1 let anotherMathFunction = addTwoInts 2 // anotherMathFunction is inferred to be of type (Int, Int) -> Int (Int, Int) -> Int 1 func printMathResult(_ mathFunction: (Int, Int) -> Int, _ a: Int, _ b: Int) { 2 print("Result: (mathFunction(a, b))") 3 } 4 printMathResult(addTwoInts, 3, 5) 5 // Prints "Result: 8" printMathResult(_:_:_:) mathFunction (Int, Int) -> Int a b Int ON THIS PAGE
  • 12.
    printMathResult(_:_:_:) addTwoInts(_:_:) 3 53 5 8 printMathResult(_:_:_:) printMathResult(_:_:_:) -> stepForward(_:) stepBackward(_:) stepForward(_:) stepBackward(_:) (Int) -> Int 1 func stepForward(_ input: Int) -> Int { 2 return input + 1 3 } 4 func stepBackward(_ input: Int) -> Int { 5 return input - 1 6 } chooseStepFunction(backward:) (Int) -> Int chooseStepFunction(backward:) stepForward(_:) stepBackward(_:) backward 1 func chooseStepFunction(backward: Bool) -> (Int) -> Int { 2 return backward ? stepBackward : stepForward 3 } chooseStepFunction(backward:) 1 var currentValue = 3 2 let moveNearerToZero = chooseStepFunction(backward: currentValue > 0) 3 // moveNearerToZero now refers to the stepBackward() function currentValue currentValue 3 currentValue > 0 true chooseStepFunction(backward:) stepBackward(_:) moveNearerToZero moveNearerToZero ON THIS PAGE
  • 13.
    1 print("Counting tozero:") 2 // Counting to zero: 3 while currentValue != 0 { 4 print("(currentValue)... ") 5 currentValue = moveNearerToZero(currentValue) 6 } 7 print("zero!") 8 // 3... 9 // 2... 10 // 1... 11 // zero! chooseStepFunction(backward:) 1 func chooseStepFunction(backward: Bool) -> (Int) -> Int { 2 func stepForward(input: Int) -> Int { return input + 1 } 3 func stepBackward(input: Int) -> Int { return input - 1 } 4 return backward ? stepBackward : stepForward 5 } 6 var currentValue = -4 7 let moveNearerToZero = chooseStepFunction(backward: currentValue > 0) 8 // moveNearerToZero now refers to the nested stepForward() function 9 while currentValue != 0 { 10 print("(currentValue)... ") 11 currentValue = moveNearerToZero(currentValue) 12 } 13 print("zero!") 14 // -4... 15 // -3... 16 // -2... 17 // -1... 18 // zero! ON THIS PAGE
  • 14.
  • 15.
  • 16.
    sorted(by:) sorted(by:) sorted(by:) sorted(by:) sorted(by:) String let names =["Chris", "Alex", "Ewa", "Barry", "Daniella"] sorted(by:) Bool true false String (String, String) -> Bool sorted(by:) 1 func backward(_ s1: String, _ s2: String) -> Bool { 2 return s1 > s2 3 } 4 var reversedNames = names.sorted(by: backward) 5 // reversedNames is equal to ["Ewa", "Daniella", "Chris", "Barry", "Alex"] ON THIS PAGE
  • 17.
    s1 s2 backward(_:_:) trues1 s2 "B" "A" "Tom" "Tim" "Barry" "Alex" a > b { ( parameters ) -> return type in statements } backward(_:_:) 1 reversedNames = names.sorted(by: { (s1: String, s2: String) -> Bool in 2 return s1 > s2 3 }) backward(_:_:) (s1: String, s2: String) -> Bool in ON THIS PAGE
  • 18.
    reversedNames = names.sorted(by:{ (s1: String, s2: String) -> Bool in return s1 > s2 } ) sorted(by:) sorted(by:) (String, String) -> Bool (String, String) Bool -> reversedNames = names.sorted(by: { s1, s2 in return s1 > s2 } ) sorted(by:) String return reversedNames = names.sorted(by: { s1, s2 in s1 > s2 } ) ON THIS PAGE
  • 19.
    sorted(by:) Bool s1 >s2 Bool return $0 $1 $2 in reversedNames = names.sorted(by: { $0 > $1 } ) $0 $1 String String > String Bool sorted(by:) reversedNames = names.sorted(by: >) ON THIS PAGE
  • 20.
    1 func someFunctionThatTakesAClosure(closure:() -> Void) { 2 // function body goes here 3 } 4 5 // Here's how you call this function without using a trailing closure: 6 7 someFunctionThatTakesAClosure(closure: { 8 // closure's body goes here 9 }) 10 11 // Here's how you call this function with a trailing closure instead: 12 13 someFunctionThatTakesAClosure() { 14 // trailing closure's body goes here 15 } sorted(by:) reversedNames = names.sorted() { $0 > $1 } () reversedNames = names.sorted { $0 > $1 } Array map(_:) map(_:) ON THIS PAGE
  • 21.
    map(_:) Int String [16,58, 510] ["OneSix", "FiveEight", "FiveOneZero"] 1 let digitNames = [ 2 0: "Zero", 1: "One", 2: "Two", 3: "Three", 4: "Four", 3 5: "Five", 6: "Six", 7: "Seven", 8: "Eight", 9: "Nine" 4 ] 5 let numbers = [16, 58, 510] numbers String map(_:) 1 let strings = numbers.map { (number) -> String in 2 var number = number 3 var output = "" 4 repeat { 5 output = digitNames[number % 10]! + output 6 number /= 10 7 } while number > 0 8 return output 9 } 10 // strings is inferred to be of type [String] 11 // its value is ["OneSix", "FiveEight", "FiveOneZero"] map(_:) number number number String output number number % 10 digitNames ON THIS PAGE
  • 22.
    digitNames ! number %10 digitNames String digitNames output number % 10 6 16 8 58 0 510 number 10 16 1 58 5 510 51 number 0 output map(_:) map(_:) makeIncrementer incrementer incrementer() runningTotal amount incrementer makeIncrementer runningTotal amount 1 func makeIncrementer(forIncrement amount: Int) -> () -> Int { 2 var runningTotal = 0 3 func incrementer() -> Int { ON THIS PAGE
  • 23.
    4 runningTotal +=amount 5 return runningTotal 6 } 7 return incrementer 8 } makeIncrementer () -> Int Int makeIncrementer(forIncrement:) runningTotal 0 makeIncrementer(forIncrement:) Int forIncrement amount runningTotal makeIncrementer incrementer amount runningTotal incrementer() 1 func incrementer() -> Int { 2 runningTotal += amount 3 return runningTotal 4 } incrementer() runningTotal amount runningTotal amount runningTotal amount makeIncrementer runningTotal incrementer ON THIS PAGE
  • 24.
    makeIncrementer let incrementByTen =makeIncrementer(forIncrement: 10) incrementByTen 10 runningTotal 1 incrementByTen() 2 // returns a value of 10 3 incrementByTen() 4 // returns a value of 20 5 incrementByTen() 6 // returns a value of 30 runningTotal 1 let incrementBySeven = makeIncrementer(forIncrement: 7) 2 incrementBySeven() 3 // returns a value of 7 incrementByTen runningTotal incrementBySeven 1 incrementByTen() 2 // returns a value of 40 incrementBySeven incrementByTen runningTotal ON THIS PAGE
  • 25.
    incrementByTen 1 let alsoIncrementByTen= incrementByTen 2 alsoIncrementByTen() 3 // returns a value of 50 4 5 incrementByTen() 6 // returns a value of 60 alsoIncrementByTen incrementByTen @escaping 1 var completionHandlers: [() -> Void] = [] 2 func someFunctionWithEscapingClosure(completionHandler: @escaping () -> Void) { 3 completionHandlers.append(completionHandler) 4 } someFunctionWithEscapingClosure(_:) @escaping ON THIS PAGE
  • 26.
    @escaping self someFunctionWithEscapingClosure(_:) self someFunctionWithNonescapingClosure(_:) self 1 funcsomeFunctionWithNonescapingClosure(closure: () -> Void) { 2 closure() 3 } 4 5 class SomeClass { 6 var x = 10 7 func doSomething() { 8 someFunctionWithEscapingClosure { self.x = 100 } 9 someFunctionWithNonescapingClosure { x = 200 } 10 } 11 } 12 13 let instance = SomeClass() 14 instance.doSomething() 15 print(instance.x) 16 // Prints "200" 17 18 completionHandlers.first?() 19 print(instance.x) 20 // Prints "100" ON THIS PAGE
  • 27.
    assert(condition:message:file:line:) condition message condition message conditionfalse 1 var customersInLine = ["Chris", "Alex", "Ewa", "Barry", "Daniella"] 2 print(customersInLine.count) 3 // Prints "5" 4 5 let customerProvider = { customersInLine.remove(at: 0) } 6 print(customersInLine.count) 7 // Prints "5" 8 9 print("Now serving (customerProvider())!") 10 // Prints "Now serving Chris!" 11 print(customersInLine.count) 12 // Prints "4" customersInLine customerProvider String () -> String 1 // customersInLine is ["Alex", "Ewa", "Barry", "Daniella"] 2 func serve(customer customerProvider: () -> String) { 3 print("Now serving (customerProvider())!") 4 } 5 serve(customer: { customersInLine.remove(at: 0) } ) 6 // Prints "Now serving Alex!" ON THIS PAGE
  • 28.
    serve(customer:) serve(customer:) @autoclosure String customerProvider @autoclosure 1 // customersInLineis ["Ewa", "Barry", "Daniella"] 2 func serve(customer customerProvider: @autoclosure () -> String) { 3 print("Now serving (customerProvider())!") 4 } 5 serve(customer: customersInLine.remove(at: 0)) 6 // Prints "Now serving Ewa!" @autoclosure @escaping @escaping 1 // customersInLine is ["Barry", "Daniella"] 2 var customerProviders: [() -> String] = [] 3 func collectCustomerProviders(_ customerProvider: @autoclosure @escaping () -> String) { 4 customerProviders.append(customerProvider) 5 } 6 collectCustomerProviders(customersInLine.remove(at: 0)) 7 collectCustomerProviders(customersInLine.remove(at: 0)) 8 9 print("Collected (customerProviders.count) closures.") 10 // Prints "Collected 2 closures." 11 for customerProvider in customerProviders { 12 print("Now serving (customerProvider())!") 13 } 14 // Prints "Now serving Barry!" 15 // Prints "Now serving Daniella!" ON THIS PAGE
  • 29.