我正试着迅速地编写以下代码:
objManager.userObject.free_credit_counter = [NSString stringWithFormat:@"%ld", [objManager.userObject.free_credit_counter integerValue]-1];我试过:
objManager.userObject.free_credit_counter = objManager.userObject.free_credit_counter - 1但我发现了一个错误:
Binary operator - cannot be applied to operands of type String! and Int发布于 2015-11-01 08:09:58
您的objManager.userObject.free_credit_counter输出值为String,在使用-运算符之前,必须将其转换为Int。
if let count = Int(objManager.userObject.free_credit_counter) {
objManager.userObject.free_credit_counter = String(count - 1)
}发布于 2015-11-01 08:09:15
错误表示您正在尝试从一个字符串值中执行1减法,这基本上是不可能的。
因此,首先让下面的字符串到int
objManager.userObject.free_credit_counter
然后减去1
发布于 2015-11-01 08:10:29
要用Swift编写完全相同的代码,您应该这样做:
objManager.userObject.free_credit_counter = NSString(format: "%ld", objManager.userObject.free_credit_counter.integerValue - 1)在您的原始代码中,您有以下内容:
[objManager.userObject.free_credit_counter integerValue]它将NSString值free_credit_counter转换为整数,整数然后递减1,然后使用格式掩码将结果转换回NSString。
在您在问题中发布的Swift代码中,缺少了对整数的转换。这就是错误告诉你的
https://stackoverflow.com/questions/33460260
复制相似问题