swift How to cast from Int? to String

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

提交回复
热议问题