I have a case where I want to check if an optional I have is Equal to a string. First I have to unwrap it to check if it exists, then I want to check if it is equal to another string. However that gives me a problem where I have to write the same code twice. I'll give you an example:
var person : Person = Person()
if let name = person.name {
if name.isEqualToString("John") {
println("Hello, John!")
}
else {
println("Wait a minute, you're not John!")
}
else {
println("Wait a minute, you're not John!")
}
As you can see, I have to write the else statement twice. Once, if the name exists and it is not 'John', and another time for when the name does not exist.
My question is, how can this be done the proper way.
Thanks for your help!
.isEqualToString
instead of==
in this case? I can’t think of one but maybe I’m missing something.==
should work with eitherNSString
orString
(or a string literal) on either side. – Backler