5

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'
    }

}
iKK
  • 6,394
  • 10
  • 58
  • 131

3 Answers3

10

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.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
5

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 :).

Chackle
  • 2,249
  • 18
  • 34
2

In Swift 3 and later, the reason for this error is that the ++ and -- operators have been removed from the language. It's recommended to use x += 1 instead.

See this very good answer for more detail on why this has happened.

Craig Brown
  • 1,891
  • 1
  • 24
  • 25
  • 1
    Why was this downvoted? Anyone who finds this page through a search for that error message will probably find this is the reason for the error (it was for me). – Craig Brown Jul 17 '18 at 11:50
  • This was my problem, not sure why you were downvoted. – Matt Jan 04 '19 at 04:45