How to avoid force unwrapping a variable?

前端 未结 5 2102
北海茫月
北海茫月 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:06

    Your instructor is, broadly speaking, correct. Definitely in this case. There's no reason for making this so special case and forcing duplicated code.

    func fullName() -> String {
        return [firstName, middleName, lastName] // The components
            .flatMap{$0}            // Remove any that are nil
            .joined(separator: " ") // Join them up
    }
    

    This just joins all the non-nil parts of the name with spaces. The other answers here are also fine, but they don't scale as well to adding more optional pieces (like a "Mr." title or "Jr." suffix).

    (This is in Swift3 syntax. Swift 2 is very similar, it's joinWithSeparator(_:) instead.)

提交回复
热议问题