【问题标题】:What is the meaning of '_ in print()' in Swift?Swift中'_ in print()'的含义是什么?
【发布时间】:2018-12-27 12:33:27
【问题描述】:

您好,我刚开始学习 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)?'

【问题讨论】:

    标签: ios iphone swift cocoa-touch


    【解决方案1】:

    此语句使用尾随闭包语法{} 之间的东西实际上是一个传递给 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.
    }
    

    如果你不打算使用 alert 动作,那么你需要 _ in 告诉 Swift 你忽略了 UIAlertAction 并且什么都不做。你是说,我知道有一个参数,但我忽略了它。

    如果你没有指定_ in,Swift 会推断你的闭包类型是() -> (),这意味着它什么也不做,也不产生任何结果。这与您期望提供的闭包类型 (UIAlertAction) -> Void 不匹配(接受 UIAlertAction 并且不返回任何内容)。

    通常是这样写的:

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

    这更清楚地表明_ in 是闭包参数语法,与print 语句没有直接关系。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-05-05
      • 1970-01-01
      • 2015-08-03
      • 2014-10-16
      • 2019-11-30
      相关资源
      最近更新 更多