Compare to nil and return a bool in Swift

前端 未结 3 1238
旧巷少年郎
旧巷少年郎 2021-01-21 03:05

UPDATE: This question is no longer a problem after Xcode beta5

Seems the beta3 release refactored how \"nil\" is working under the hood but didn\'t com

相关标签:
3条回答
  • 2021-01-21 03:24

    The release notes of XCode 6 Beta 5 state the following:

    Optionals no longer conform to the BooleanType (formerly LogicValue) protocol, so they may no longer be used in place of boolean expressions (they must be explicitly compared with v != nil). This resolves confusion around Bool? and related types, makes code more explicit about what test is expected, and is more consistent with the rest of the language.

    Note that ImplicitlyUnwrappedOptional still includes some BooleanType functionality. This !issue will be resolved in a future beta. (17110911)!

    This means your previous approach should work again:

    func hasLogin() -> Bool {
        return self.credentail != nil
    }
    
    0 讨论(0)
  • 2021-01-21 03:43

    This was working for me:

    func hasLogin() -> Bool {
        return self.credential ? true : false
    }
    
    0 讨论(0)
  • 2021-01-21 03:46

    The under-the-covers method that Swift uses to turn non-Bool values in booleans for use in if statements is the getLogicValue() method of the LogicValue protocol (which Optional implements):

    func hasLogin() -> Bool {
        return self.credential.getLogicValue()
    }
    
    0 讨论(0)
提交回复
热议问题