【问题标题】:concatenate in swift: Binary operator '+' cannot be applied to operands of type 'String' and 'AnyObject'快速连接:二元运算符“+”不能应用于“String”和“AnyObject”类型的操作数
【发布时间】:2015-10-08 08:49:08
【问题描述】:

我在 Swift 中收到错误,但在执行此操作时不明白:

if(currentUser["employer"] as!Bool == false) { print("employer is false: "+currentUser["employer"] as!Bool) }

但我可以做到(虽然它实际上并没有打印任何东西,也许是另一个问题):

if(currentUser["employer"] as!Bool == false) { 打印(当前用户[“雇主”])}

导致错误:

二元运算符“+”不能应用于“字符串”类型的操作数和 '任何对象'

同样:

                let currentUser = PFUser.currentUser()!
                let isEmployer = currentUser["employer"]
                print("isEmployer: \(isEmployer)")
                print(currentUser["employer"])

但这两个不起作用:

                print("employer: "+currentUser["employer"])
                print("employer: \(currentUser["employer"])")

我也碰巧使用 Parse 来获取数据,也不确定这是否正确。

【问题讨论】:

  • 你能指定错误吗?
  • 错误在标题中,原样:二进制运算符'+'不能应用于'String'和'AnyObject'类型的操作数

标签: parse-platform concatenation swift2


【解决方案1】:

第一个示例中的错误消息可能具有误导性

if currentUser["employer"] as! Bool == false { 
 print("employer is false: "+currentUser["employer"] as! Bool) 
}

在这种情况下,错误信息应该是

二元运算符“+”不能应用于“字符串”和“布尔”类型的操作数

因为currentUser["employer"] as! Bool 是非可选的Bool,不能隐式转换为String

那些例子

print("employer: "+currentUser["employer"])
print("employer: \(currentUser["employer"])")

不工作,因为

  • 在第一行中,不带任何类型转换的currentUser["employer"] 是一个不知道+ 运算符的可选AnyObject(又名未指定)。
  • 在第二行中,字符串插值表达式中的字符串文字"employer" 会导致语法错误(在 Xcode 7.1 beta 2 中已修复)。

编辑:

这种语法是通常的方式。

let isEmployer = currentUser["employer"]
print("isEmployer: \(isEmployer)")

或者,你可以写

print("employer is " + String(currentUser["employer"] as! Bool))

【讨论】:

  • 好的。所以最后一个例子将是未来添加的一个特性,但前两个是转换错误,只是 swift 无法完成的事情?
  • 可以的。您的代码let isEmployer = currentUser["employer"] print("isEmployer: \(isEmployer)") 是正确的方法。或者你可以写print("employer is " + String(currentUser["employer"] as! Bool))
  • print("employer is " + String(currentUser["employer"] as!Bool)) 是我要找的……这太乏味了!但现在我清楚地明白发生了什么。所以我应该先把它自己转换成一个变量。有了简单的东西,我已经摆脱了使用 +。谢谢。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-13
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2019-02-13
  • 1970-01-01
相关资源
最近更新 更多