Josue Espinosa Josue Espinosa - 7 months ago 136
Swift Question

Swift 2 - Proper way to concatenate optional strings?

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
}


I understand optionals, but I can't quite wrap my head around the "Swift" way of thinking about them and dealing with unwrapping safely. Are we just supposed to nest
if let
's? Is there a cleaner, more "Swift" way of doing the above? 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.

Answer

flatMap would work well here, with joinWithSeparator:

let f: String? = "jo"
let l: String? = "smith"

[f,l] // "jo smith"
  .flatMap{$0}
  .joinWithSeparator(" ")

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

let n: String? = nil

[f,n] // "jo"
  .flatMap{$0}
  .joinWithSeparator(" ")