Josue Espinosa Josue Espinosa - 2 years ago 307
Swift Question

Swift 2 - Proper way to concatenate optional strings?

Let's assume I've got a

class instance named
name properties which are both optional strings.

Now I want to construct a
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


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 Source

flatMap would work well here, with joinWithSeparator:

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

[f,l] // "jo smith"
  .joinWithSeparator(" ")

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

let n: String? = nil

[f,n] // "jo"
  .joinWithSeparator(" ")
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download