Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Proper way to concatenate optional swift strings?

Tags:

swift

Let's assume I've got a Person class instance named person with first and last name properties which are both optional strings.

Now I want to construct a fullName string that contains either just their first or last name (if that's all that is available), or if we have both, their first and last name with a space in the middle.

var fullName : String? if let first = person.first {     name = first } if let last = person.last {     if name == nil {         name = last     } else {         name! += " " + last     } } 

or

var name = "" if let first = person.first {     name = first } if let last = person.last {     name = name.characters.count > 0 ? name + " " + last : last } 

Are we just supposed to nest if let's? Nil coalescing seems appropriate but I can't think of how to apply it in this scenario. I can't help but feeling like I'm doing optional string concatenation in an overly complicated way.

like image 590
Josue Espinosa Avatar asked Nov 24 '15 23:11

Josue Espinosa


People also ask

Which is the correct way to concatenate 2 strings?

You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs. For string variables, concatenation occurs only at run time.

Can you concatenate an empty string?

Concatenating with an Empty String VariableYou can use the concat() method with an empty string variable to concatenate primitive string values. By declaring a variable called totn_string as an empty string or '', you can invoke the String concat() method to concatenate primitive string values together.


1 Answers

compactMap would work well here, combined with .joined(separator:):

let f: String? = "jo" let l: String? = "smith"  [f,l] // "jo smith"   .compactMap { $0 }   .joined(separator: " ") 

It doesn't put the space between if one is nil:

let n: String? = nil  [f,n] // "jo"   .compactMap { $0 }   .joined(separator: " ") 
like image 191
oisdk Avatar answered Sep 22 '22 09:09

oisdk