Checking the value of an Optional Bool

后端 未结 6 533
情书的邮戳
情书的邮戳 2021-01-30 10:13

When I want to check if an Optional Bool is true, doing this doesn\'t work:

var boolean : Bool? = false
if boolean{
}

It results in this error:

6条回答
  •  伪装坚强ぢ
    2021-01-30 10:33

    var enabled: Bool? = true
    
    if let enabled = enabled, enabled == true {
        print("when is defined and true at the same moment")
    }
    
    if enabled ?? false {
        print("when is defined and true at the same moment")
    }
    
    if enabled == .some(true) {
        print("when is defined and true at the same moment")
    }
    
    if enabled == (true) {
        print("when is defined and true at the same moment")
    }
    
    if case .some(true) = enabled {
        print("when is defined and true at the same moment")
    }
    
    if enabled == .some(false) {
        print("when is defined and false at the same moment")
    }
    
    if enabled == (false) {
        print("when is defined and false at the same moment")
    }
    
    if enabled == .none {
        print("when is not defined")
    }
    
    if enabled == nil {
        print("when is not defined")
    }
    

提交回复
热议问题