[英]Binary operator - cannot be applied to operands of type String! and Int
I am trying to write the following line of code in swift: 我试图快速编写以下代码行:
objManager.userObject.free_credit_counter = [NSString stringWithFormat:@"%ld", [objManager.userObject.free_credit_counter integerValue]-1];
i tried : 我试过了 :
objManager.userObject.free_credit_counter = objManager.userObject.free_credit_counter - 1
but I'm getting this error : 但我收到此错误:
Binary operator - cannot be applied to operands of type String! and Int
Your objManager.userObject.free_credit_counter
output value is String
and you have to convert it to Int
before use -
operator 你objManager.userObject.free_credit_counter
输出值是String
,你必须把它转换为Int
使用前-
运营商
if let count = Int(objManager.userObject.free_credit_counter) {
objManager.userObject.free_credit_counter = String(count - 1)
}
the error says that you are trying to do subtraction by 1 from a string value , basically which is not possible. 该错误表明您正在尝试从字符串值中 减去1 ,基本上是不可能的。
So, first make the bellow string to int 因此,首先将波纹管字符串设置为int
objManager.userObject.free_credit_counter objManager.userObject.free_credit_counter
and then subtract by 1 然后减去1
To have exactly the same code written in Swift you should do: 要使用Swift编写完全相同的代码,您应该执行以下操作:
objManager.userObject.free_credit_counter = NSString(format: "%ld", objManager.userObject.free_credit_counter.integerValue - 1)
In your original code you have this bit: 在原始代码中,您需要:
[objManager.userObject.free_credit_counter integerValue]
It converts the NSString
value of free_credit_counter
to an integer, which is then decremented by 1, and then the result is converted back to NSString
using a format mask. 它将free_credit_counter
的NSString
值转换为整数,然后将其减1,然后使用格式掩码将结果转换回NSString
。
In the Swift code that you have posted in the question, the conversion to integer is missing. 在问题中发布的Swift代码中,缺少到整数的转换。 That's what the error tells you about 那就是错误告诉你的
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.