Swift: Testing optionals for nil

前端 未结 14 616
攒了一身酷
攒了一身酷 2020-12-08 08:51

I\'m using Xcode 6 Beta 4. I have this weird situation where I cannot figure out how to appropriately test for optionals.

If I have an optional xyz, is the correct w

相关标签:
14条回答
  • 2020-12-08 09:28

    To add to the other answers, instead of assigning to a differently named variable inside of an if condition:

    var a: Int? = 5
    
    if let b = a {
       // do something
    }
    

    you can reuse the same variable name like this:

    var a: Int? = 5
    
    if let a = a {
        // do something
    }
    

    This might help you avoid running out of creative variable names...

    This takes advantage of variable shadowing that is supported in Swift.

    0 讨论(0)
  • 2020-12-08 09:28

    If you have conditional and would like to unwrap and compare, how about taking advantage of the short-circuit evaluation of compound boolean expression as in

    if xyz != nil && xyz! == "some non-nil value" {
    
    }
    

    Granted, this is not as readable as some of the other suggested posts, but gets the job done and somewhat succinct than the other suggested solutions.

    0 讨论(0)
  • 2020-12-08 09:29

    Also you can use Nil-Coalescing Operator

    The nil-coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil. The expression a is always of an optional type. The expression b must match the type that is stored inside a.

    let value = optionalValue ?? defaultValue
    

    If optionalValue is nil, it automatically assigns value to defaultValue

    0 讨论(0)
  • 2020-12-08 09:31

    Instead of if, ternary operator might come handy when you want to get a value based on whether something is nil:

    func f(x: String?) -> String {
        return x == nil ? "empty" : "non-empty"
    }
    
    0 讨论(0)
  • 2020-12-08 09:31
    var xyz : NSDictionary?
    
    // case 1:
    xyz = ["1":"one"]
    // case 2: (empty dictionary)
    xyz = NSDictionary() 
    // case 3: do nothing
    
    if xyz { NSLog("xyz is not nil.") }
    else   { NSLog("xyz is nil.")     }
    

    This test worked as expected in all cases. BTW, you do not need the brackets ().

    0 讨论(0)
  • 2020-12-08 09:32

    Another approach besides using if or guard statements to do the optional binding is to extend Optional with:

    extension Optional {
    
        func ifValue(_ valueHandler: (Wrapped) -> Void) {
            switch self {
            case .some(let wrapped): valueHandler(wrapped)
            default: break
            }
        }
    
    }
    

    ifValue receives a closure and calls it with the value as an argument when the optional is not nil. It is used this way:

    var helloString: String? = "Hello, World!"
    
    helloString.ifValue {
        print($0) // prints "Hello, World!"
    }
    
    helloString = nil
    
    helloString.ifValue {
        print($0) // This code never runs
    }
    

    You should probably use an if or guard however as those are the most conventional (thus familiar) approaches used by Swift programmers.

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