在 swift 中连接:二元运算符“+”不能应用于 'String' 和 'AnyObject' 类型的操作数
concatenate in swift: Binary operator '+' cannot be applied to operands of type 'String' and 'AnyObject'
我在 Swift 中遇到错误,并且在执行此操作时不理解它:
if(currentUser["employer"] as! Bool == false) { print("employer is
false: "+currentUser["employer"] as! Bool) }
但我可以做到(虽然它实际上没有打印任何东西,也许是另一个问题):
if(currentUser["employer"] as! Bool == false) {
print(currentUser["employer"]) }
结果错误:
Binary operator '+' cannot be applied to operands of type 'String' and
'AnyObject'
同样:
let currentUser = PFUser.currentUser()!
let isEmployer = currentUser["employer"]
print("isEmployer: \(isEmployer)")
print(currentUser["employer"])
但是这两个不行:
print("employer: "+currentUser["employer"])
print("employer: \(currentUser["employer"])")
我也恰好在使用 Parse 获取数据,但也不确定这是否是正确的方法。
第一个示例中的错误消息可能具有误导性
if currentUser["employer"] as! Bool == false {
print("employer is false: "+currentUser["employer"] as! Bool)
}
在这种情况下,错误信息应该是
binary operator '+' cannot be applied to operands of type 'String' and '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 中遇到错误,并且在执行此操作时不理解它:
if(currentUser["employer"] as! Bool == false) { print("employer is false: "+currentUser["employer"] as! Bool) }
但我可以做到(虽然它实际上没有打印任何东西,也许是另一个问题):
if(currentUser["employer"] as! Bool == false) { print(currentUser["employer"]) }
结果错误:
Binary operator '+' cannot be applied to operands of type 'String' and 'AnyObject'
同样:
let currentUser = PFUser.currentUser()!
let isEmployer = currentUser["employer"]
print("isEmployer: \(isEmployer)")
print(currentUser["employer"])
但是这两个不行:
print("employer: "+currentUser["employer"])
print("employer: \(currentUser["employer"])")
我也恰好在使用 Parse 获取数据,但也不确定这是否是正确的方法。
第一个示例中的错误消息可能具有误导性
if currentUser["employer"] as! Bool == false { print("employer is false: "+currentUser["employer"] as! Bool) }
在这种情况下,错误信息应该是
binary operator '+' cannot be applied to operands of type 'String' and '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))