Open4

swift クロージャの書き方

nenenene

クロージャでの処理結果をラベルで表示できるようにした

nenenene
// 与えた数値を足し算した後、labelとして表示する
showResult(x: 5, y: 2)

// labelとして表示するための処理は書いて、計算する処理 + 計算後の表示はplusにお願いしてる
func showResult(x: Int, y: Int) {
    plus(x: x, y: y, complete: { sum in
        label.text = String(sum)
    })
}

// 受け取った値を足し算して、その後にcompleteの処理を実行してる
func plus(x: Int, y: Int, complete: (Int) -> Void) {
    let sum = x + y
    complete(sum)
}

nenenene

2つ以上にまたがる場合

// 与えた数値を足し算した後、10倍してlabelとして表示する
showResult(x: 5, y: 2)
  
// labelとして表示するための処理は書いて、計算する処理 + 計算後の表示はplusにお願いしてる
func showResult(x: Int, y: Int) {
    plus(x: x, y: y, complete: { sum in
        label.text = String(sum)
    })
}

// 受け取った値を足し算して、10倍する処理 + 計算後の表示はtenTimesにお願いしてる
func plus(x: Int, y: Int, complete: (Int) -> Void) {
    let sum = x + y

    tenTimes(x: sum, complete: complete)
}

// 受け取った値を10倍したあと、completeの処理 (= labelに表示する処理)を実行する
func tenTimes(x: Int, complete: (Int) -> Void) {
    let result = 10 * x
    complete(result)
}