簡體   English   中英

Swift中'_ in print()'的含義是什么?

[英]What is the meaning of '_ in print()' in Swift?

嗨,我剛剛開始學習Swift。 我只是學習ios開發的初學者。

func showOkay() {
    let title = NSLocalizedString("a title", comment: "")
    let message = NSLocalizedString("msg", comment: "")
    let cansal = NSLocalizedString("cancel", comment: "")
    let ok = NSLocalizedString("ok", comment: "")
    let alertController = UIAlertController (title: title, message: message, preferredStyle: .alert)

    let cancelAlertAction = UIAlertAction (title : cansal, style : .cancel) {
        _ in print("cancel") // i don't understand this line . its just a print or somthing else. why i cant use print here.
    }
    let okAction = UIAlertAction(title: ok , style : .default) {
        _ in print("ok") // i don't understand this line. its just a print or somthing else. why i cant use print here.
    }

    alertController.addAction(cancelAlertAction)
    alertController.addAction(okAction)
    present(alertController, animated: true, completion: nil)
}

@IBAction func btnAction(_ sender: Any) {
     showOkay()
}

如果我只使用print()它們會給我像

無法將類型'()->()'的值轉換為期望的參數類型'((UIAlertAction)-> Void)?

該語句使用結尾閉包語法 {}之間的內容實際上是一個閉包,它傳遞給UIAlertAction ,以便在事件發生時稍后調用。 調用閉包時,它將傳遞所創建的UIAlertAction對象。

let cancelAlertAction = UIAlertAction (title : cansal , style : .cancel) {
    _ in print("cancel") \\ i don't understand this line . its just a print or somthing else . why i cant use print here.
}

如果您不打算使用警報動作,則需要使用_ in來告訴Swift您將忽略UIAlertAction並對其不執行任何操作。 您是說,我知道有一個參數,但我忽略了它。

如果您未指定_ in ,則Swift會將您的閉包類型推斷為() -> () ,這意味着它什么也不做也不產生任何東西。 這與您期望提供的閉包類型(UIAlertAction) -> Void不匹配(采用UIAlertAction返回任何內容)。

通常這樣寫:

let cancelAlertAction = UIAlertAction (title : cansal , style : .cancel) { _ in
    print("cancel")
}

這樣可以更清楚地知道_ in是閉包參數語法,並且與print語句沒有直接關系。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM