Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Unary operator ++ cannot be applied to an operand of type Int

Why does the following swift code bring me the error "Unary operator '++' cannot be applied to an operand of type 'Int'" ??? (using swift-1.2 on Xcode-6.3.2)

struct Set {

    var player1Games: Int
    var player2Games: Int

    init() {
        self.player1Games = 0
        self.player2Games = 0
    }

    func increasePlayer1GameScore () {
        player1Games++   // error: Unary operator '++' cannot be applied to an operand of type 'Int'
    }

    func increasePlayer2GameScore () {
        player2Games++   // error: Unary operator '++' cannot be applied to an operand of type 'Int'
    }

}
like image 617
iKK Avatar asked May 27 '15 08:05

iKK


2 Answers

The error message is a bit misleading. What you need to do is add mutating before func to specify that it will modify the struct:

struct MySet {

    var player1Games: Int
    var player2Games: Int

    init() {
        self.player1Games = 0
        self.player2Games = 0
    }

    mutating func increasePlayer1GameScore() {
        player1Games++
    }

    mutating func increasePlayer2GameScore() {
        player2Games++
    }

}

Note: Set is a type in Swift, I would suggest to use a different name for your struct.

like image 184
Eric Aya Avatar answered Sep 22 '22 16:09

Eric Aya


Use the mutating keyword before a function declaration to indicate you're mutating the class variables.

OR

Change your struct to a class.

This should fix your issues :).

like image 44
Chackle Avatar answered Sep 19 '22 16:09

Chackle