navit navit - 2 months ago 6
Swift Question

Concatenate literal with Optional String

Whats the proper way to implement this ? preferably in one line.

var name: String?
...
let username = "@" + name


Note:
username
must be
String?
I don't want to unwrap
name
for concatenation.

Edit: if
name
is
nil
,
username
should also be
nil
.

Answer

You can use the map method of Optional:

let username = name.map { "@" + $0 }

If name is nil then the closure is not executed and the result is nil. Otherwise the closure is evaluated with $0 set to the unwrapped name.

Comments