2016-11-07 102 views
1

Q:是否可以在Swift 3中將函數作爲函數參數傳遞?如何在Swift 3中將函數設置爲函數參數

爲了重構我的代碼,我想要一個全局函數。在這個函數結束時,有一個自定義按鈕,它有一個action參數。

let deleteButton = MIAlertController.Button(title: "cancel", 
              type: .cancel, 
              config: getDestructiveButtonConfig(), 
              action: { 
               print("completed") 
              }) 

我想要做的就是,用一個函數作爲參數設置一個全局函數。

MyGlobalStuff.swift 
... 
func getButton(_ myFunc: func, _ title: String) { 
    let deleteButton = MIAlertController.Button(title: title, 
              type: .cancel, 
              config: getDestructiveButtonConfig(), 
              action: { 
               myFunc // call here the function pass by argument 
              }) 
} 

通過getButton(..)調用,並在同一個類中傳遞函數。

MyViewController.swift 
... 
getButton(myPrintFunc, "cancel") 

func myPrintFunc() { 
     print("completed") 
} 

是這樣的可能嗎?非常感謝幫助。

+3

你在找這個? '函數類型作爲參數類型'在https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Functions.html – Santosh

+0

@Santosh你的鏈接不包括我的問題。我不在尋找關閉或返回值 –

+0

好。實際上我需要一個關閉......我發誓,我已經嘗試過。不工作。答案後再次嘗試,工作......我的壞。謝謝你或你的時間 –

回答

7

是你可以傳遞一個函數/閉包作爲另一個函數的參數。

這是語法

func doSomething(closure:() ->()) { 
    closure() 
} 

這裏的功能doSomething接收沒有PARAMS和沒有返回類型閉包作爲參數。

可以調用DoSomething的這個語法

doSomething(closure: { _ in print("Hello world") }) 

或者使用尾隨閉包語法

doSomething { 
    print("Hello world") 
} 
+0

閉包不起作用,因爲這個代碼會在getButton函數被調用的那一刻被調用,而不是一旦按下按鈕 –

+2

@DavidSeek,爲什麼在getButton函數被調用的時候它會被執行? – user28434

+0

如果我在getButton中有一個閉包,它將在函數完成時被調用。但是我需要在按下按鈕後調用它 –

2

函數是迅速一流的,所以你可以像這樣通過他們:

func getButton(_ myFunc:() -> Void, _ title: String) { 

您需要指定類型的函數,即參數類型的簽名和返回類型

+0

謝謝,你的方法和appzYourLife一樣好。給他勾號,因爲他速度更快。 upvote爲您的時間和幫助。謝謝 –

4

假設

typealias Func =() -> Void  

你可以這樣做:

func getButton(_ title: String, _ myFunc: Func) { 
    let deleteButton = MIAlertController.Button(title: title, 
               type: .cancel, 
               config: getDestructiveButtonConfig(), 
               action: { 
                myFunc() 
               }) 
} 

甚至:

func getButton(_ title: String, _ myFunc: Func) { 
    let deleteButton = MIAlertController.Button(title: title, 
               type: .cancel, 
               config: getDestructiveButtonConfig(), 
               action: myFunc 
               ) 
} 

另外,如果您有沒有注意到,我搬到封閉到參數列表的末尾。這樣就會讓高級的魔法,如:

getButton("X") { … } 

,而不是

getButton({ … }, "X") 
+0

呃。我喜歡typealias。謝謝!爲此贊成 –

相關問題