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 it makes the code look simpler and because of the if check the variable ! is called on will never be nil and so cannot crash.
My instructor introduced us to the bang(!) operator and then told us to never use it again. Telling us why of course, that it will crash our app if the optional is nil.
However I find myself in situations like these where the bang operator seems to be the most concise and safe option.
func fullName() -> String {
if middleName == nil {
return "(firstName) (lastName)"
}else{
return "(firstName) (middleName!) (lastName)"
}
}
Is there a better way to do something like this?
Also, here's the full class if anybody is wondering.
class CPerson{
var firstName: String
var middleName: String?
var lastName: String
init(firstName: String, middleName: String?, lastName: String) {
self.firstName = firstName
self.middleName = middleName
self.lastName = lastName
}
convenience init(firstName: String, lastName: String) {
self.init(firstName: firstName, middleName: nil, lastName: lastName)
}
func fullName() -> String {
if middleName == nil {
return "(firstName) (lastName)"
}else{
return "(firstName) (middleName!) (lastName)"
}
}
}
My instructor said "If I see you using the bang operator, we're going to fight" O_O
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…