2017-06-03 152 views
-2

尋找傳遞一個函數作爲一個參數(如onCompletion),將作爲Swift函數調用的一部分(類似於JavaScript閉包)調用。這裏最好的做法是什麼?如何將函數作爲函數swift的參數傳遞?

代碼:

func didFinishFunc(onCompletion: func) { 
    func() 
} 

func onCompletionFunc() 
{ 
    print("completed.") 
} 

func caller() 
{ 
    didFinishFunc(onCompletion: onCompletionFunc) 
} 

// caller is called 
caller() 
+1

閱讀swift語言指南。 https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/TheBasics.html – Alexander

+0

感謝您的詳細回覆 – KingChintz

+1

我不會浪費時間寫一個精心準備的回答,如果你已經做了盡職調查,並且在來這裏之前閱讀了語言指南或搜索了Google搜索,那麼這些問題很容易回答。你有3個反對票是有原因的。 – Alexander

回答

3

你可以像這樣定義你的功能。

func didFinishFunc(onCompletion:() -> Void) { 
    // your function implementation here 

    onCompletion() 
} 

這個函數在一個封閉件(有時被稱爲一個回調或其他語言的匿名函數)作爲參數。這個閉包沒有參數,也沒有返回值。

如果你想關閉有參數,你可以做這樣的事情:

func didFinishFunc(onCompletion: (String, Int) -> Void) { 
    // your function implementation here 

    onCompletion("foo", 5) 
} 

這個函數有兩個參數的StringInt

如果您希望封閉具有返回類型,請在->之後更改類型(在Void之上)。

+0

完美的感謝泰勒 – KingChintz

相關問題