![](/img/trans.png)
[英]Should self be captured as strong in a UIAlertAction's handler?
[英]Right way to make a UIAlertAction's handler
似乎有3種不同的方式來編寫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
這些都是制作人嗎? 有什么區別,並且最好使用嗎?
它們都是一樣的,這主要是您偏愛的句法風格。 選項3使用類型推斷和尾隨閉包語法,由於它簡潔明了,因此通常被首選,因為它將最后一個參數閉包移到函數調用之外,因此避免了多余的括號。 您可以通過刪除action
周圍的括號來選擇一個選項3,這些括號也不需要。
更多有關此內容的信息,請參見Swift編程語言一書,請參見閉包部分。
都是一樣的。 由於swift是一種強類型語言,因此無需將動作定義為UIAlertAction
, UIAlertAction
,coz UIAlertAction
的init方法將其定義為UIAlertAction
。 就像在從該數組中檢索值時使用某些自定義類定義數組時一樣,無需像在Objective C中那樣將其強制轉換。
所以以上三種方式中的任何一種都可以,數字3似乎很清楚,符合我的口味:)
另外,由於它沒有返回類型,因此也無需提及Void(return type)。 如果它具有返回類型,則需要提及,例如param -> RetType in
method { param -> String in
return "" // should return a String value
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.