【问题标题】:cannot convert value of type 'UILabel!' to expected argument 'type inout String'无法转换“UILabel!”类型的值到预期的参数“输入输出字符串”
【发布时间】:2017-07-11 22:16:01
【问题描述】:

当我尝试增加currentNumberAdmin 我得到:

无法转换“UILabel!”类型的值到预期的参数“输入输出字符串”

class adminPanel: UIViewController {

    @IBOutlet weak var currentNumberAdmin: UILabel!                       

    @IBAction func nextCurrent(_ sender: UIButton) {
        let database = FIRDatabase.database().reference()
        database.child("current").observe(FIRDataEventType.value, with: { (snapshot) in

          self.currentNumberAdmin.text = snapshot.value as! String
          currentNumberAdmin += String(1)
        })

    }
}

有谁知道我如何正确转换和增加currentNumberAdmin

【问题讨论】:

  • 为什么要在视图中添加字符串?你想达到什么目的?

标签: ios swift


【解决方案1】:

因为这条线:currentNumberAdmin += String(1) 导致崩溃。您正在尝试将 String 值添加到 UILabel 值,这是无效的。您实际上是在告诉编译器将 UILabel currentNumberAdmin(一个 UILabel)分配给将 UILabel 添加到 String 的表达式的值,编译器不知道如何执行此操作,因此会出现异常消息。

不完全清楚为什么您要尝试设置标签的文本两次:一次使用 snapshot.value,然后再次设置下一行。如果您尝试将标签的文本设置为快照值 + 1,请执行以下操作:

@IBAction func nextCurrent(_ sender: UIButton) {
    let database = FIRDatabase.database().reference()
    database.child("current").observe(FIRDataEventType.value, with: { (snapshot) in

      var strVal = Int(self.currentNumberAdmin.text)!
      strVal += 1
      self.currentNumberAdmin.text = String(strVal)
    })

}

【讨论】:

  • 抱歉没有提到 snapshot.value 属性为 Any?
  • 当我尝试将其转换为 int 时,出现此错误:无法使用类型为 '(Any?)' 的参数列表调用类型为 'int' 的初始化程序
  • @EliasKnudsen 如果您只是想每次将文本的值增加 1,您只需要每次来回转换值。我已经更新了我的示例以反映这一点。一个警告是,如果 currentNumberAdmin.text 包含非数字值,这将崩溃。例如。如果标签包含“hi”,它将崩溃,但如果它包含“0”,它将按预期工作。
  • 当我使用你写的代码时,它建议放一个!在这样的参数中:“var strVal = Int(self.currentNumberAdmin.text!)!”。当我运行它时,它在展开可选值时意外发现 nil。
  • 您要么需要在界面生成器中将标签的初始值设置为0,要么需要在代码中添加检查(可能更安全)以确保该值不为空,这表示测试字符串“”。
猜你喜欢
  • 2019-12-24
  • 2021-09-18
  • 2018-11-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-12
相关资源
最近更新 更多