Check for nil with guard instead of if?

前端 未结 4 963
孤独总比滥情好
孤独总比滥情好 2020-12-30 01:48

Is there a guard equivalent of checking if a variable is nil? If so how would I translate a statement like this to use guard instead?<

相关标签:
4条回答
  • 2020-12-30 02:18

    You can use guards with let.

    guard let preview = post["preview"] else {
       //handle case where the variable is nil
    }
    
    0 讨论(0)
  • 2020-12-30 02:25

    I think you might want a guard-let construction, like this:

    guard let preview = post["preview"] else { */ nil case */ }
    
    /* handle non-nil case here... preview is non-nil */
    
    0 讨论(0)
  • 2020-12-30 02:30

    Like some people already answered, you can use let

    guard let preview = post["preview"] else { /* Handle nil case */ return }
    

    If you are not using the variable, you can use an underscore to not declare the variable and avoid the warning.

    guard let _ = post["preview"] else { /* Handle nil case */ return }
    

    You can also do a regular boolean check instead of using let

    guard post["preview"] != nil else { /* Handle nil case */ return }
    

    A more general case for a boolean check on a guard

    guard conditionYouExpectToBeTrue else { /* Handle nil case */ return }
    

    If you want to be able to modify the variable, you can use var instead of let

    guard var preview = post["preview"] else { /* Handle nil case */ return }
    

    Swift 3.0

    You can combine var/let with a boolean check by using commas between the statements.

    guard let preview = post["preview"], preview != "No Preview" else { /* Handle nil case */ return }
    

    Swift 2.x

    You can combine var/let with the boolean check by using where where

    guard let preview = post["preview"] where preview != "No Preview" else { /* Handle nil case */ return }
    
    0 讨论(0)
  • 2020-12-30 02:36

    You can use guard to grab the value from the post dictionary:

    guard let value = post["preview"] else {
        return  // or break, or throw, or fatalError, etc.
    }
    // continue using `value`
    
    0 讨论(0)
提交回复
热议问题