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
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:
if letguardif-elseAnd 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.