swift How to cast from Int? to String

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

    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 ?? ""
    
    0 讨论(0)
  • 2021-02-03 21:10

    You can try this to convert Int? to string

    let myString : String = "42"
    let x : Int? = myString.toInt()
    
    let newString = "\(x ?? 0)"
    print(newString)        // if x is nil then optional value will be "0"
    
    0 讨论(0)
  • 2021-02-03 21:11

    Hope this helps

    var a = 50
    var str = String(describing: a)
    
    0 讨论(0)
  • 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!)
    
    0 讨论(0)
  • 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 ?? ""
    
    0 讨论(0)
  • 2021-02-03 21:16

    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
    
    0 讨论(0)
提交回复
热议问题