Validating optional isEqualToString

I have a case where I want to check if I have an option equal to the string. First I have to expand it to check if it exists, then I want to check if it matches another line. However, this gives me a problem when I have to write the same code twice. I will 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 need to write an else statement twice. Once, if the name exists, and this is not "John", but another time, when the name does not exist.

My question is: how can this be done properly.

Thanks for your help!

+5
source share
4 answers

Optional has the == operator defined for it in the Swift standard library:

 func ==<T : Equatable>(lhs: T?, rhs: T?) -> Bool 

This means that if the option contains an equivalent value, you can compare two additional parameters. If both parameters are equal to zero, and if two optional values ​​are equal, then they are equal.

So, if you don’t care if person.name nil or not, it just contains the value β€œJohn”, you can simply write if person.name == "John" .

How does it work when "John" is a String not a String? ? * Since Swift will implicitly convert any type to an optional wrapper, enter if this is what the argument requires. So how does the == function require a String? argument to compare options String? , "John" will be implicitly converted to {Some "John"} , which allows you to use the == operator between two options.

* well, actually, "John" is not a String , its string literal, which is converted to String

+9
source
 var person : Person = Person() let name = person.name if (name != nil && name! == "John") { println("Hello, John!") } else { println("Wait a minute, you're not John!") } 
+1
source

Since you are testing three different conditions, the correct value, the wrong value or lack of value, there will be some amount of duplication.

This can be minimized by extracting duplication in a new method, for example:

 func notJohn() { println("Wait a minute, you're not John!") } if let name = person.name { if (name == "John") { println("Hello, John") } else { notJohn() } } else { notJohn() } 
0
source

I am not familiar with Swift, not sure if this is your answer.

 let name = person.name if name == "John" { println("Hello, John!") } else{ println("Wait a minute, you're not John!") } 
-2
source

Source: https://habr.com/ru/post/1209580/


All Articles