swift How to cast from Int? to String

前端 未结 11 1279
天命终不由人
天命终不由人 2021-02-03 20:42

In Swift, i cant cast Int to String by:

var iString:Int = 100
var strString = String(iString)

But my variable in Int? , there for error:

11条回答
  •  醉梦人生
    2021-02-03 21:15

    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 ?? ""
    

提交回复
热议问题