Swift3 從入門到精通Day6:閉包Closure

Alice
Daily Swift
Published in
2 min readMay 14, 2017

時間:5/12(五)

內容:

  • 41. 閉包:沒有名字的函式7:05
  • 42. 閉包:有型別可當函式參數的閉包6:09
  • 43. 閉包:可以當作函式回傳值的閉包6:46
  • 44. 閉包:省略簡寫方法5:20
  • 45. 閉包:閉包與陣列的 Map 方法10:50
  • 46. 閉包:閉包與陣列的 Filter方法3:34

41. 閉包:沒有名字的函式

Closure閉包:沒有名字的函式

函式轉Closure的步驟

  1. 刪除關鍵字func 刪除函式名稱
  2. 把參數跟回傳值一到大括號中
  3. 加入in

let helloClosure = {“Hello Everbody”}

helloClosure()

func eat(foodName:String){

“I want to eat \(foodName)”

}

eat(foodName: “Pizza”)

//How to chage to Closure

let eatClosure = {

(foodName:String) in

“I want to eat \(foodName)”}

eatClosure(“apple pie”)

func add(number1:Int,number2:Int) -> Int{

let result = number1 + number2

return result

}

add(number1: 3, number2: 13)

//How to chage to Closure

let addClosure = {

(number1:Int,number2:Int) -> Int in

let result = number1 + number2

return result

}

add(number1: 3, number2: 13)

func multuply(number1:Int,number2:Int) -> String {

return “\(number1) * \(number2) = \(number1 * number2)”

}

multuply(number1: 4, number2: 3)

//How to chage to Closure

let multuplyClosure = {(number1:Int,number2:Int) -> String in

return “\(number1) * \(number2) = \(number1 * number2)”

}

multuply(number1: 4, number2: 3)

  • 42. 閉包:有型別可當函式參數的閉包6:09

func calculate(num1:Int,num2:Int,operation:(Int,Int) -> (Int)){

print(operation(num1,num2))

}

calculate(num1: 3, num2: 8, operation: addClosure)

  • 43. 閉包:可以當作函式回傳值的閉包6:46
  • 44. 閉包:省略簡寫方法5:20
  1. 已經能夠確認的參數與回傳值的型別的話,可以刪除Closure裡面的參數跟回傳值。
  2. 程式碼只有一行的情況下,可以刪除return
  3. 用$0 $1等,代替傳進來的參數名稱。
  4. 如果是最後或唯一的參數,可以把Closure移至參數小括號外。
  5. 如果是唯一參數,可省略參數小括號。

let addClosure:(Int,Int)->(Int) = {

(number1:Int,number2:Int) -> Int in

return = number1 + number2

}

////簡化

let addClosure:(Int,Int)->(Int) = { $0 + $1 }

  • 45. 閉包:閉包與陣列的 Map 方法10:50

var numberArray = [1,2,5,7,9,2,4,6,8,10]

numberArray.count

//加入numberArray.append(27)

let numberArrayAddTen = numberArray.map({

(number:Int) ->Int in

return number+20

})

numberArrayAddTen

let numberArrayToString =

numberArray.map({

(a:Int) -> String in

return”This is number \(a)”

})

numberArrayToString

//簡略

  1. 已經能夠確認的參數與回傳值的型別的話,可以刪除Closure裡面的參數跟回傳值。
  2. 程式碼只有一行的情況下,可以刪除return
  3. 用$0 $1等,代替傳進來的參數名稱。
  4. 如果是最後或唯一的參數,可以把Closure移至參數小括號外。
  5. 如果是唯一參數,可省略參數小括號。

let numberArrayAddTen = numberArray.map{$0+20}

let numberArrayToString =numberArray.map{

“This is number \($0)”

}

  • 46. 閉包:閉包與陣列的 Filter方法3:34

var numberArray = [1,2,5,7,9,2,4,6,8,10]

numberArray.filter({

(number:Int) ->Bool in

return number % 2 == 0

})

numberArray.filter({

(number:Int) ->Bool in

return number > 5

})

//簡化

let evenNumber = numberArray.filter{ $0 %2 ==0 }

let evenNumber = numberArray.filter{ $0 > 5 }

--

--