How to avoid force unwrapping a variable?

前端 未结 5 2106
北海茫月
北海茫月 2020-11-30 13:56

How do I avoid using the ! operation doing a force unwrap as using this is usually a bad option.

What is the better option with code like the following where using

5条回答
  •  孤城傲影
    2020-11-30 14:00

    Before unwrapping an optional variable you should must check for nil otherwise your app will crash if variable contain nil. And checks can be performed in several ways like:

    1. if let
    2. guard
    3. if-else
    4. using ternary operator
    5. Nil coalescing operator

    And which one to use completely depends on requirement.

    You can just replace this code

    if middleName == nil {
        return "\(firstName) \(lastName)"
    }else{
        return "\(firstName) \(middleName!) \(lastName)"
    }
    

    by

    return "\(firstName)\(middleName != nil ? " \(middleName!) " : " " )\(lastName)"
    

    OR

    you can also use Nil coalescing operator (a ?? b) unwraps an optional a if it contains a value, or returns a default value b if a is nil.

提交回复
热议问题