3

I just update Xcode to 7.3 and now I get this warning:

'var' parameters are deprecated and will be removed in Swift 3

I need to use the var in this function:

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
        }
    }
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Ahmed Safadi
  • 433
  • 1
  • 6
  • 19

1 Answers1

5

UPDATE: I've reworded my answer because I thought you actually wanted inout, but you don't. So...

The motivation can be found here. The tl;dr is: var gets confused with inout and it doesn't add much value, so get rid of it.

Therefore:

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

Becomes:

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

Therefore your code would become:

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
        }
    }
}
Michael
  • 8,891
  • 3
  • 29
  • 42
  • i try that , but the same problem http://i.imgur.com/WSggY1Z.png – Ahmed Safadi Mar 24 '16 at 03:58
  • At least you fixed my brain-freeze where I used `let` instead of `var`. However, you don't have the `a:` in the function definition. Is this what's causing your problem now? – Michael Mar 24 '16 at 04:01
  • nah it's there , but the problem is that the fix tell me to delete it ! , and there's no var in function oO – Ahmed Safadi Mar 24 '16 at 04:03
  • 1
    This is working for me in IBM's sandbox (I don't have XCode on this machine). Maybe try doing a Clean and restarting XCode? By the way, you can shorten your code in the first `if` to `return a ?? b ?? 0`. – Michael Mar 24 '16 at 04:06
  • I wrote a [shorter implementation](https://swiftlang.ng.bluemix.net/#/repl/5758d1517bd71c1f315cf6c2). (Bluemix may not work properly in Safari.) – Franklin Yu Jun 09 '16 at 02:19