How to avoid force unwrapping a variable?

Use the if let or guard constructs:

func fullName() -> String {
    if let middleName = middleName {
        return "\(firstName) \(middleName) \(lastName)"

    } else {
        return "\(firstName) \(lastName)"
    }
}

func fullName() -> String {
    guard let middleName = middleName else {
        return "\(firstName) \(lastName)"
    }
    return "\(firstName) \(middleName) \(lastName)"
}

I’ve put the guard statement in for completeness but as others have commented this is more commonly used in an error/failure case.

I would also advise against using string interpolation for Strings. They are already strings, there is no need to use the description of each name in a new string.

Consider return firstName + " " + lastName. See Difference between String interpolation and String initializer in Swift for cases when string interpolation could return an unexpected result.

Leave a Comment