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.
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.
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.
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: " ")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With