Swift3 optionals chaining in IF conditions bug?

后端 未结 4 672
感动是毒
感动是毒 2020-12-01 20:01

This code worked just fine in Swift 2.3 and I don\'t understand why I have to unwrap TestClass to check if number is bigger than 4. This is whole point of chain

相关标签:
4条回答
  • 2020-12-01 20:42

    It's not a bug. It is, alas, intentional. Implicit unwrapping of optionals in comparisons (>) has been removed from the language.

    So, the problem now is that what's on the left side of the > is an Optional, and you can no longer compare that directly to 4. You have to unwrap it and get an Int, one way or another.

    0 讨论(0)
  • 2020-12-01 20:52

    Optional comparison operators are removed from Swift 3. SE-0121

    You need to write something like this:

    if test?.optionalInt ?? 0 > 4
    {
    
    }
    
    0 讨论(0)
  • 2020-12-01 20:57

    This could also happen on Guard statement. Example:

    var playerLevels = ["Harry": 25, "Steve": 28, "Bob": 0]
    

    for (playerName, playerLevel) in playerLevels {

    guard playerLevels > 0 else {//ERROR !!
        print("Player \(playerName) you need to do the tutorial again !")
        continue
    }
    
    print("Player \(playerName) is at Level \(playerLevels)")
    

    }

    0 讨论(0)
  • 2020-12-01 20:59

    First of all, where are you initialising your test var? Of course it'll be nil if you don't give it a value!

    And regarding optional chaining, what's the issue writing :

    if let optionalInt = test?.optionalInt, optionalInt > 4
    {
    
    }
    

    As always, safety > brevity.

    0 讨论(0)
提交回复
热议问题