Nata Mio
Nata Mio

Reputation: 2226

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

Upvotes: 0

Views: 1006

Answers (3)

0x416e746f6e
0x416e746f6e

Reputation: 10136

To have exactly the same code written in Swift you should do:

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.

In the Swift code that you have posted in the question, the conversion to integer is missing. That's what the error tells you about

Upvotes: 0

Alexey Pichukov
Alexey Pichukov

Reputation: 3405

Your objManager.userObject.free_credit_counter output value is String and you have to convert it to Int before use - operator

if let count = Int(objManager.userObject.free_credit_counter) {
    objManager.userObject.free_credit_counter = String(count - 1)
}

Upvotes: 1

Jamil
Jamil

Reputation: 2999

the error says that you are trying to do subtraction by 1 from a string value, basically which is not possible.

So, first make the bellow string to int

objManager.userObject.free_credit_counter

and then subtract by 1

Upvotes: 0

Related Questions