Combine a literal with an optional string

What is the right way to implement this? preferably in one line.

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

Note: it usernamemust be String?I do not want to deploy namefor concatenation.

Edit: if name- nil, usernameshould also be nil.

+2
source share
4 answers

You can use the method map Optional:

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

If name- nil, then the closure is not performed, but the result nil. Otherwise, the closure is evaluated using the $0set to the expanded name.

+11
source

Try it:

let username = name.flatMap { "@\($0)" }
+3
source

EDITED :

. :

var name: String?
var username: String?

if let name = name {
  username = "@" + name
} 
+1
source

The easiest and most readable option is likely to use if let, but you can also determine the method prependa String, the opposite String.append, and then use an optional chain:

extension String {
    func prepending(prefix: String) -> String {
        return prefix + self
    }
}

var name: String?
let username = name?.prepending("@")
0
source

Source: https://habr.com/ru/post/1658263/


All Articles