2016-11-14 48 views
1

我想知道是否有人可以幫助我運行3個函數,依靠前一個函數的信息來工作。 這是我從以前的帖子上找到的代碼怎麼弄2工作:迅速運行3個函數一個接一個

func firstTask(completion: (success: Bool) -> Void) { 
    // Do something 

    // Call completion, when finished, success or faliure 
    completion(success: true) 
} 

//And use your completion block like this: 
firstTask { (success) -> Void in 
    if success { 
     // do second task if success 
     secondTask() 
    } 
} 

但是,如果你想它的第二個完成運行後會在哪裏第三功能去? 對不起,如果這是一個非常基本的問題,但我仍然得到編程和Swift的懸念。

感謝您的幫助!

+1

再次使用相同的模式。 'secondTask {......... //如果成功則執行第三個任務}' – Thilo

+0

@Thilo這是相當反面的模式。它使功能綁定到連鎖店。它們不是可重複使用/模塊化的 – Alexander

+0

好吧,它在Niko的答案中看起來非常整齊。但是,是的,你可能想拉一些圖書館來避免回調 - 地獄。 – Thilo

回答

1

最好將結果作爲返回值返回,並使用中間變量鏈接在一起。

儘量避免過度使用完成處理程序。他們可以使代碼異常難以瀏覽。儘可能優先使用返回值。

func produceASCIIHexCodes() -> [UInt8] { 
    return [0x48, 0x65, 0x6c, 0x6c, 0x6f, 0x2c, 0x20, 0x57, 0x6f, 0x72, 0x6c, 0x64, 0x21] 
} 

func convertToUnicodeScalars(hexCodes: [UInt8]) -> [UnicodeScalar] { 
    return hexCodes.map(UnicodeScalar.init) 
} 

func convertToCharacters(unicodeScalars: [UnicodeScalar]) -> [Character] { 
    return unicodeScalars.map(Character.init) 
} 

func createString(fromCharacters characters: [Character]) -> String { 
    return String(characters) 
} 

func display(string: String) { 
    print(string) 
} 

let hexCodes = produceASCIIHexCodes() 
let unicodeScalars = convertToUnicodeScalars(hexCodes: hexCodes) 
let characters = convertToCharacters(unicodeScalars: unicodeScalars) 
let string = createString(fromCharacters: characters) 
display(string: string) 
1

您可以這樣聲明它(經測試,在操場上)

import UIKit 
import Foundation 

func firstTask() -> Bool { 
    // Do something 
    print("First task") 
    return true // change this to determine the task success or not 
} 

func secondTask() -> Bool { 
    // Do something 
    print("Second task") 
    return true // change this to determine the task success or not 
} 

func thirdTask() { 
    // Do something 
    print("Third task") 
} 

let thirdBlock: (_ success: Bool) ->() = { success in 
    guard success else { return } 
    thirdTask() 
} 

let secondBlock: (_ success: Bool) ->() = { success in 
    guard success else { return } 
    let success = secondTask() 
    thirdBlock(success) 
} 

let firstBlock:() ->() = { 
    let success = firstTask() 
    secondBlock(success) 
} 

firstBlock() 

您可以從學習反應式編程這個回調地獄救自己,無論是與ReactiveCocoaRxSwift