0

I'm writing this very simple completion handler, but then now I have this error in my case saying :

error: '>' is not a prefix unary operator

I looked here but that doesn't seem to answer my question. I added space between the operator and 5 but still it didn't work. I'm sure the fix is simple but I couldn't figure it out. All other cases for Ints I've seen had a range, but this is just a comparison

func completeTasks(number: Int, completionHandler : (_ flag : Bool) -> () ){
    switch number {
    case <5 :
        completionHandler(true)
    case >5 :
        completionHandler(false)
    default:
        fatalError()
    }
}

completeTasks(number: 10){ result in print(result)
}
Community
  • 1
  • 1
mfaani
  • 33,269
  • 19
  • 164
  • 293
  • Your code doesn't work simply because `<5` isn't a valid pattern – as the linked Q&A shows, you can *bind* to a variable, then do the comparison in a `where` clause (or skip the binding and just compare the number directly in the `where` clause). Also note that your code doesn't handle the case `number == 5` ;) – Hamish Jan 26 '17 at 15:04
  • @Hamish You're possibly the best commenter for the iOS community, knowing all the previous questions :D. was just messing around to see a crash :D. btw. I really didn't like the accepted answer. [This](http://stackoverflow.com/a/41148638/5175709) is great, while [this](http://stackoverflow.com/a/31661367/5175709) is a good hack. The accepted answer is just not Swifty and too much work. Don't you agree? – mfaani Jan 26 '17 at 15:17
  • 1
    Glad to be of help :) To be honest, it really depends on your preference – in your case, as you're working with an `Int`, another alternative would be [this one](http://stackoverflow.com/a/31657319/2976878). Personally, I don't mind the accepted answer (binding then comparison in the `where` clause) – IMO it's still short enough to be easily readable and feels the least 'hacky'. – Hamish Jan 26 '17 at 15:26
  • In your special case I would probably simply use if statements: `if number < 5 { } else if { number > 5 } else { fatalError() }` ... – Martin R Jan 26 '17 at 15:39
  • @Hamish why isn't a valid pattern? I mean a parameter is passed in, just as it's passed in for say `case 1...4:`. – mfaani Jan 26 '17 at 15:45
  • @Honey It works for `case 1...4` because `~=` (the pattern matching operator) is overloaded for ranges. `<5` as a lone expression doesn't resolve to anything – therefore it would either have to be made [a pattern](https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Patterns.html) – or `<` would have to be overloaded to be a (pre/post)fix operator to return some value which can be used in a `~=` overload. – Hamish Jan 26 '17 at 16:07

0 Answers0