swift How to cast from Int? to String

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

    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

    0 讨论(0)
  • 2021-02-03 21:18

    Sonrobby, I believe that "Int?" means an optional int. Basically, by my understanding, needs to be unwrapped.

    So doing the following works fine:

    let y: Int? = 42
    let c = String(y!)
    

    That "!" unwraps the variable. Hope this helps!

    As rakeshbs mentioned, make sure the variable won't be nill.

    0 讨论(0)
  • 2021-02-03 21:19

    For preventing unsafe optional unwraps I use it like below as suggested by @AntiStrike12,

     if let theString = someVariableThatIsAnInt  {        
        theStringValue = String(theString!))
     }
    
    0 讨论(0)
  • 2021-02-03 21:23

    Swift 3:

    var iString:Int = 100
    var strString = String(iString)
    extension String {
        init(_ value:Int){/*Brings back String() casting which was removed in swift 3*/
            self.init(describing:value)
        }
    }
    

    This avoids littering your code with the verbose: String(describing:iString)

    Bonus: Add similar init methods for commonly used types such as: Bool, CGFloat etc.

    0 讨论(0)
  • 2021-02-03 21:26

    Crude perhaps, but you could just do:

    let int100 = 100
    println(int100.description) //Prints 100
    
    0 讨论(0)
提交回复
热议问题