2016-08-05 90 views
0

似乎有3種不同的方式來編寫UIAlertAction的處理程序。每下方似乎做我希望他們同/預期的事情製作UIAlertAction的處理程序的正確方法

// 1. 
let okAction = UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: {(action: UIAlertAction!) -> Void in 
    print("a") 
}) 

// 2. 
let okAction = UIAlertAction(title: "OK", style: .Default, handler: { (action: UIAlertAction!) in 
    print("b") 
}) 

// 3. 
let okAction = UIAlertAction(title: "OK", style: .Default) { (action) in 
    print("c") 
} 

// OUTPUT: 
// a 
// b 
// c 

難道這些都使處理程序?有什麼區別,最適合使用?

+0

這個鏈接應該幫助http://stackoverflow.com/questions/24190277/writing-handler-for-uialertaction – gurmandeep

+0

@gurmandeep感謝。我仍然想明白爲什麼3.是最好的,他們之間的差異都是 – rdk

+0

我同意@Joey。更多詳情請參閱https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIAlertAction_Class/ – gurmandeep

回答

2

它們都是一樣的,它主要是你喜歡的句法風格問題。選項3使用類型推斷和尾隨閉包語法,因爲它簡潔並且在函數調用之外移動最後一個參數閉包時除去了多餘的括號集,所以通常是首選。您可以通過刪除action附近的括號來選擇3,這些都不是必需的。

更多相關內容請參閱Swift Programming Language書中的說明,請參閱閉包一節。

0

其全部相同。由於swift是一種強類型語言,不需要將動作定義爲UIAlertAction,因此的init方法將其定義爲UIAlertAction。 就像當你從數組中檢索值時定義一個數組的定製類一樣,你不需要像在目標C中那樣施放它。

因此,上述3種方法中的任何一種都可以,3號似乎是清晰的,爲我的口味:)

也因爲它沒有返回類型沒有必要提及Void(返回類型)了。如果它有一個返回類型,你需要一提的是像param -> RetType in

method { param -> String in 
     return "" // should return a String value 
} 
相關問題