Home > Software engineering >  What is the purpose of calling text.flatMap(URL.init)?
What is the purpose of calling text.flatMap(URL.init)?

Time:06-29

What is the purpose of calling text.flatMap(URL.init) in the following:

guard let url = someUITextField.text.flatMap(URL.init) else {
 return true
}

someUITextField.text is assumed to have a URL string that a user entered.

CodePudding user response:

text is an optional and URL(init) returns also an optional. The result is a double optional URL??

flatMap first transforms the String? to URL?? then it removes one ? to be able to if let the expression.

Please read What’s the difference between map(), flatMap() and compactMap()? on hackingwithswift for details.

  • Related