3

我刚刚将 Xcode 更新到 7.3,现在我收到了这个警告:

'var' 参数已弃用,将在 Swift 3 中删除

我需要在这个函数中使用 var:

class func gcdForPair(var a: Int?, var _ b: Int?) -> Int {
    // Check if one of them is nil
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    // Swap for modulo
    if a < b {
        let c = a
        a = b
        b = c
    }

    // Get greatest common divisor
    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b! // Found it
        } else {
            a = b
            b = rest
        }
    }
}
4

1 回答 1

5

更新:我改写了我的答案,因为我认为你真的想要inout,但你没有。所以...

动机可以在这里找到。tl;dr 是:var被混淆inout并且没有增加太多价值,所以摆脱它。

所以:

func myFunc(var a: Int) {
    ....
}

变成:

func myFunc(a: Int) {
    var a = a
    ....
}

因此,您的代码将变为:

class func gcdForPair(a: Int?, _ b: Int?) -> Int {
    var a = a
    var b = b
    // Check if one of them is nil
    if b == nil || a == nil {
        if b != nil {
            return b!
        } else if a != nil {
            return a!
        } else {
            return 0
        }
    }

    // Swap for modulo
    if a < b {
        let c = a
        a = b
        b = c
    }

    // Get greatest common divisor
    var rest: Int
    while true {
        rest = a! % b!

        if rest == 0 {
            return b! // Found it
        } else {
            a = b
            b = rest
        }
    }
}
于 2016-03-24T03:34:32.927 回答