swift How to cast from Int? to String

You can use string interpolation.

let x = 100
let str = "\(x)"

if x is an optional you can use optional binding

var str = ""
if let v = x {
   str = "\(v)"
}
println(str)

if you are sure that x will never be nil, you can do a forced unwrapping on an optional value.

var str = "\(x!)"

In a single statement you can try this

let str = x != nil ? "\(x!)" : ""

Based on @RealMae's comment, you can further shorten this code using the nil coalescing operator (??)

let str = x ?? ""

Optional Int -> Optional String:

If x: Int? (or Double? - doesn't matter)

var s = x.map({String($0)})

This will return String?

To get a String you can use :

var t = s ?? ""

If you need a one-liner it can be achieved by:

let x: Int? = 10
x.flatMap { String($0) } // produces "10"
let y: Int? = nil
y.flatMap { String($0) } // produces nil

if you need a default value, you can simply go with

(y.flatMap { String($0) }) ?? ""

EDIT:

Even better without curly brackets:

y.flatMap(String.init)

Apple's flatMap(_:) Documentation


I like to create small extensions for this:

extension Int {
    var stringValue:String {
        return "\(self)"
    }
}

This makes it possible to call optional ints, without having to unwrap and think about nil values:

var string = optionalInt?.stringValue

Tags:

Swift