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: Cant invoke 'init' with type '@Ivalue Int?'
Example
let myString : String = "42" let x : Int? = myString.toInt() if (x != null) { // Successfully converted String to Int //And how do can i convert x to string??? }
We can convert int to String in java using String. valueOf() and Integer. toString() methods.
The next method in this list to convert int to string in C++ is by using the to_string() function. This function is used to convert not only the integer but numerical values of any data type into a string. The to_string() method is included in the header file of the class string, i.e., <string> or <cstring>.
Xcode 8.1 / Swift 3.0.1 Attention (Swift 4): If you have a string like let a="a,,b,c" and you use a. split(separator: ",") you get an array like ["a", "b", c"] by default. This can be changed using omittingEmptySubsequences: false which is true by default. Any multi-character splits in Swift 4+?
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 ?? ""
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With