swift How to cast from Int? to String

前端 未结 11 1284
天命终不由人
天命终不由人 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:11

    You need to "unwrap" your optional in order to get to the real value inside of it as described here. You unwrap an option with "!". So, in your example, the code would be:

    let myString : String = "42"
    let x : Int? = myString.toInt()
    
    if (x != null) {
        // Successfully converted String to Int
        // Convert x (an optional) to string by unwrapping
        let myNewString = String(x!)
    }
    

    Or within that conditional, you could use string interpolation:

    let myNewString = "\(x!)" // does the same thing as String(x!)
    

提交回复
热议问题