3 回答

TA貢獻1995條經驗 獲得超2個贊
假設您具有從網絡下載文件的下載功能,并且希望在下載任務完成時收到通知。
typealias CompletionHandler = (success:Bool) -> Void
func downloadFileFromURL(url: NSURL,completionHandler: CompletionHandler) {
// download code.
let flag = true // true if download succeed,false otherwise
completionHandler(success: flag)
}
// How to use it.
downloadFileFromURL(NSURL(string: "url_str")!, { (success) -> Void in
// When download completes,control flow goes here.
if success {
// download success
} else {
// download fail
}
})
希望能幫助到你。

TA貢獻1785條經驗 獲得超8個贊
簡單的Swift 4.0示例:
func method(arg: Bool, completion: (Bool) -> ()) {
print("First line of code executed")
// do stuff here to determine what you want to "send back".
// we are just sending the Boolean value that was sent in "back"
completion(arg)
}
如何使用它:
method(arg: true, completion: { (success) -> Void in
print("Second line of code executed")
if success { // this will be equal to whatever value is set in this method call
print("true")
} else {
print("false")
}
})

TA貢獻2065條經驗 獲得超14個贊
我在理解答案時遇到了麻煩,因此我假設像我這樣的任何其他初學者都可能遇到與我相同的問題。
我的解決方案與最高答案相同,但希望對于初學者或一般難以理解的人更加清晰易懂。
使用完成處理程序創建函數
func yourFunctionName(finished: () -> Void) {
print("Doing something!")
finished()
}
使用功能
override func viewDidLoad() {
yourFunctionName {
//do something here after running your function
print("Tada!!!!")
}
}
您的輸出將是
做某事
多田
希望這可以幫助!
- 3 回答
- 0 關注
- 779 瀏覽
添加回答
舉報