一元运算符++不能应用于Int类型的操作数 [英] Unary operator ++ cannot be applied to an operand of type Int

查看:449
本文介绍了一元运算符++不能应用于Int类型的操作数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为什么下面的快速代码给我带来错误一元运算符'++'不能应用于'Int'类型的操作数??? (在Xcode-6.3.2上使用swift-1.2)

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

}


推荐答案

错误消息有点误导。您需要做的是 func 之前添加变异以指定它将修改结构:

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

}

注意: Set 是Swift中的一个类型,我建议为你的结构使用不同的名称。

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

这篇关于一元运算符++不能应用于Int类型的操作数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆