Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

swift How to cast from Int? to String

Tags:

swift

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??? } 
like image 906
Sonrobby Avatar asked Feb 03 '15 03:02

Sonrobby


People also ask

Can you cast from int to string?

We can convert int to String in java using String. valueOf() and Integer. toString() methods.

Can you cast int to string C++?

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>.

How do I split a string in Swift 4?

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+?


2 Answers

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 ?? "" 
like image 147
rakeshbs Avatar answered Oct 04 '22 15:10

rakeshbs


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 
like image 44
Antoine Avatar answered Oct 04 '22 15:10

Antoine