Swift good coding practice: If statement with optional type Bool

前端 未结 3 1157
独厮守ぢ
独厮守ぢ 2021-01-04 11:48

So I\'ve been developing an app in Swift, and today I spent nearly an hour debugging a problem that turned out to be completely unexpected. It all resulted from the code bel

相关标签:
3条回答
  • 2021-01-04 12:03

    my advice is to use this nice coalescing ??

    if textfieldDate.text?.isEmpty ?? true {
        // the text is either nil or empty but its all we want to know
    }
    
    0 讨论(0)
  • 2021-01-04 12:14

    If the bool is part if Core Data (aka NSNumber), you should do it like this.

    if (isHero.isAI?.boolValue != nil)
    

    Regards

    0 讨论(0)
  • 2021-01-04 12:15

    This is a known issue that is being tracked on the SwiftInFlux repo, which includes this quote from Chris Lattner on the Apple developer forums.

    This problem exists with any optional of something that conforms to the LogicValue protocol (e.g. nested optionals, optional of bool, etc). We consider it serious issue that needs to be fixed for 1.0 and have some ideas, but haven't settled on a solution yet.

    So, this issue doesn't just effect optional Bools, but any optional type that conforms to the LogicValue protocol (defined as).

    protocol LogicValue {
        func getLogicValue() -> Bool
    }
    

    Anyway as far as recommendations on how to work around this go, it's hard to recommend any one specific solution considering that Apple hasn't given an indication of how they intend to solve this in the future, but I would imagine that continuing to explicitly check the value of the Bool would be the way to go.

    if (hero.isAI == true) {
        // stuff    
    }
    

    In fact, after some further reading, the quote listed above continues to read:

    For this common case, the simplest answer would be to produce a warning for "if x" and require someone to explictly write "if x != nil" or "if x == true" to make it explicit what they want.

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