在 Basic Operators 一节中,Swift Programming Language guide 指出++ 是一个有效的运算符:



但是,在操场上尝试此操作时:

class Levels {
    var data = [
        [
            "nodesNum" : 20,
            "lastLevel" : false
        ],
        [
            "nodesNum" : 16,
            "lastLevel" : false
        ],
        [
            "nodesNum" : 13,
            "lastLevel" : false
        ],
        [
            "nodesNum" : 10,
            "lastLevel" : false
        ],
        [
            "nodesNum" : 8,
            "lastLevel" : true
        ]
    ]
}

var levels: Levels!
var availableNodesNum: Int!
var currentLevelData: NSDictionary!
var levelNum:Int = 2

levels = Levels()

currentLevelData = levels.data[levelNum]
availableNodesNum = Int(currentLevelData["nodesNum"]! as! NSNumber)

println(currentLevelData)
println(availableNodesNum)

availableNodesNum++

构建错误显示:



为什么?感谢您的帮助

最佳答案

你应该先打开它

availableNodesNum!++

因为在标准库中 ++ 只为非可选项定义为前缀和后缀运算符。
prefix public func ++(inout x: UInt8) -> UInt8

prefix public func ++(inout rhs: Float80) -> Float80

postfix public func ++(inout lhs: Double) -> Double

postfix public func ++(inout lhs: Float) -> Float

prefix public func ++(inout rhs: Float) -> Float

postfix public func ++(inout x: Int) -> Int

prefix public func ++(inout x: Int) -> Int

postfix public func ++(inout x: UInt) -> UInt

prefix public func ++(inout x: UInt) -> UInt

/// Replace `i` with its `successor()` and return the original
/// value of `i`.
postfix public func ++<T : _Incrementable>(inout i: T) -> T

postfix public func ++(inout x: Int64) -> Int64

prefix public func ++(inout x: Int64) -> Int64

postfix public func ++(inout x: UInt64) -> UInt64

prefix public func ++(inout x: UInt64) -> UInt64

/// Replace `i` with its `successor()` and return the updated value of
/// `i`.
prefix public func ++<T : _Incrementable>(inout i: T) -> T

postfix public func ++(inout x: Int32) -> Int32

prefix public func ++(inout x: Int32) -> Int32

postfix public func ++(inout x: UInt32) -> UInt32

postfix public func ++(inout lhs: Float80) -> Float80

prefix public func ++(inout x: UInt32) -> UInt32

postfix public func ++(inout x: Int16) -> Int16

prefix public func ++(inout x: Int16) -> Int16

postfix public func ++(inout x: UInt16) -> UInt16

prefix public func ++(inout x: UInt16) -> UInt16

postfix public func ++(inout x: Int8) -> Int8

prefix public func ++(inout x: Int8) -> Int8

postfix public func ++(inout x: UInt8) -> UInt8

prefix public func ++(inout rhs: Double) -> Double

& 请记住,根据 documentation :



如果您使用带有可选的一元运算符,您将得到相同的错误
var a : Int? = 12
a++ //Unary operator '++' cannot be applied to an operand of type 'Int?'

关于swift 一元运算符 '++' 不能应用于 'Int!' 类型的操作数,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/31930423/

10-12 01:32
查看更多