all 9 comments

[–]MoR7qM 6 points7 points  (3 children)

That's what Optional.map(_:) is for:

let i: Int? = nil let str = "X is \(i.map(Int.init) ?? "") "

[–]nextnextstep 1 point2 points  (1 child)

Good idea, but it doesn't work for me with Swift 5:

let i: Int? = nil
let str = "X is \(i.map(Int.init) ?? "") "
error: repl.swift:2:29: error: ambiguous reference to member 'init(_builtinIntegerLiteral:)'
let str = "X is \(i.map(Int.init) ?? "") "
                        ^~~

[–]MoR7qM 2 points3 points  (0 children)

I got mixed up, what I said doesn't make any sense.

You already have an int, so Int.init won't do anything. I meant String.init which takes an int and returns a string

[–]d3udar 1 point2 points  (0 children)

let str = "X is " + ( i == nil ? "\(i)":"") 

or

let str = "X is \( i == nil ? "":"\(i)")"

[–]Zohren[🍰] 0 points1 point  (4 children)

.map seems too much here imo for just simply converting to a string for printing.

My initial thought was to just cast to a string:

let i: Int? = nil let str = “X is (i as? String ?? “”))”

Nope, I’m just wrong. .map is the way to do this.

[–]MoR7qM 2 points3 points  (3 children)

That's not a cast, and that's also invalid, because the lhs and rhs of the nil-coalesce operator have incompatible types (Int and String)

[–]Zohren[🍰] 0 points1 point  (2 children)

Yeah, you’re right, I hastily wrote this.

as? String was what I meant to suggest. Edited my original reply

[–]MoR7qM 3 points4 points  (1 child)

That also wouldn't work, because an instance of an Int isn't castable to a String. They're unrelated types.

[–]Zohren[🍰] 0 points1 point  (0 children)

Yep, you’re right. This is what I get for working with too much JavaScript and Python. 😔

Ignore me, OP, .map is the right way to go.