有型別可當參數的閉包


各式型別

var telNumber:Int = 9
var willYouMarryMe:Bool = true
var numberArray:[Int] = [3,33,5,9]

練習:請將下面的閉包hello everybody加入型別

let helloClosure = { "hello everybody" }
helloClosure()

解答:

let helloClosure:()->() = { "hello everybody" }
helloClosure()
//加入型別":()->() "
//沒有參數,也以有回傳值

練習:請將下面的閉包加入型別

let eatClosure = {
    (foodName:String) in
    "I want to have \(foodName)"
}
eatClosure("apple")

解答:

let eatClosure:(String)->() = {
    (foodName:String) in
    "I want to have \(foodName)"
}
eatClosure("apple")
//加入型別":(String)->()"
//有參數,沒回傳值

練習:請將下面的閉包加入型別

let addClosure = {
    (number1:Int, number2:Int) -> Int in
    let result = number1 + number2
    return result
}
addClosure(3, 8)

//產出結果:"11"

解答:

let addClosure:(Int,Int) -> (Int) = {
    (number1:Int, number2:Int) -> Int in
    let result = number1 + number2
    return result
}
addClosure(3, 8)

//加入型別":(Int,Int)->(Int)"
//意思:接受二個整數當參數->回傳字串的型別
//產出結果:"11"

練習:請將下面的閉包Multiply加入型別

let multiplyClosure = {
    (number1:Int, number2:Int) ->String in
    return "\(number1) * \(number2) = \(number1 * number2)"
}
multiplyClosure(5,7)
//產出結果:"5 * 7 = 35"

解答:

let multiplyClosure2:(Int,Int)->(String) = {
    (number1:Int, number2:Int) ->String in
    return "\(number1) * \(number2) = \(number1 * number2)"
}
multiplyClosure2(5,7)

//加入型別":(Int,Int)->(String)"
//意思:接受二個整數當參數->回傳字串的型別
//產出結果:"5 * 7 = 35"

Closure可以當作是一個值


Closure是一個值,所以可以當成函數的參數

範例:
let addClosure:(Int,Int) -> (Int) = {
    (number1:Int, number2:Int) -> Int in
    let result = number1 + number2
    return result
}
addClosure(3, 8)


func cal(num1:Int, num2:Int, operation:(Int,Int)->(Int)){
    print(operation(num1, num2))
}
cal(num1: 3, num2: 8, operation: addClosure)

//三個參數:num1, num2, operation
//其中operation的型別是:接受二個整數, 回傳整數的『Closure』
//把閉包 cal當作一個參數,代入『num1 =3, num2 =8』, 代入到addClosure
//而addClosure,也剛好是接受二個整數,回傳整數
//整段程式碼的解釋:代入3跟8的數字,再把3跟8代入addClosure裡面去計算
//輸出結果:"11"

results matching ""

    No results matching ""