Condition after variable binding in guard swift compilation issue

454 Views Asked by At

I am using the nice guard statement from Swift 3.0 (in Xcode 8.0) and have the following function:

func parse(suffix s: String) throws -> Instruction {
    guard let count = Int(s) where count >= 0 else {
      throw InstructionParsingError(message: s + " should be a positive integer")
    }
    return CallInstruction(argCount: count)
}

My issue is that the swift compiler complains twice about the line containing my guard statement:

CallInstruction.swift:42:29: Boolean condition requires 'where' to separate it from variable binding
CallInstruction.swift:42:30: Expected ',' joining parts of a multi-clause condition

I tried

  • replacing the where with a , then the second error disappears but the first one is still there.
  • replacing the where with , where but then this line can't even be parsed
  • replacing the count in the where by Int(s) but have the same errors.

How should I change my code so that it compiles? (With a nice single guard statement I mean, of course I could have multiple guards, or ifs or switch but from what I read about the guard statement I should be able to have a clean readable line).

1

There are 1 best solutions below

0
Oleg Gordiichuk On

For solving of this issue i recommend you to use model Swift syntax in guard statement that replace where with ,.

func  parse(suffix s: String) {
    guard let count = Int(s), count >= 0 else {
         return
    }
}

Also it is possible to use if let statement :

func  parseTwo(suffix s: String) {
    if let count = Int(s), count >= 0  {
        // done
        print(count)
    } else {
        return
    }
}