Convert Int to String in Swift
646,007
Solution 1
Converting Int
to String
:
let x : Int = 42
var myString = String(x)
And the other way around - converting String
to Int
:
let myString : String = "42"
let x: Int? = myString.toInt()
if (x != nil) {
// Successfully converted String to Int
}
Or if you're using Swift 2 or 3:
let x: Int? = Int(myString)
Solution 2
Check the Below Answer:
let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
Solution 3
Here are 4 methods:
var x = 34
var s = String(x)
var ss = "\(x)"
var sss = toString(x)
var ssss = x.description
I can imagine that some people will have an issue with ss. But if you were looking to build a string containing other content then why not.
Solution 4
In Swift 3.0:
var value: Int = 10
var string = String(describing: value)
Solution 5
Swift 4:
let x:Int = 45
let str:String = String(describing: x)
Developer.Apple.com > String > init(describing:)
The String(describing:) initializer is the preferred way to convert an instance of any type to a string.
Author by
Steve Marshall
Fledgling programmer, living in Brighton, UK. Trying to figure out iOS.
Updated on July 15, 2022Comments
-
Steve Marshall almost 2 years
I'm trying to work out how to cast an
Int
into aString
in Swift.I figure out a workaround, using
NSNumber
but I'd love to figure out how to do it all in Swift.let x : Int = 45 let xNSNumber = x as NSNumber let xString : String = xNSNumber.stringValue
-
Gabriele Petronella almost 10 yearsmeh, this is an ugly and unnecessary workaround when
String
already has a constructor acceptingInt
-
PREMKUMAR almost 10 yearswhat wrong you find this? why you put down vote? @GabrielePetronella
-
Desty almost 10 yearsI don't think this is particularly ugly, except that some parsing tools may not handle string interpolation nicely. Otherwise, who knows -- it might faster. Using ""+x in Javascript is generally faster than using a String constructor, for example. This example is only a couple of characters shorter, but I would certainly prefer string interpolation in cases where you were constructing a sentence from several variables.
-
Isuru over 9 yearsI wouldn't downvote this answer just because its ugly but as @GabrielePetronella said, there's no need to use string interpolation when
String
has a constructor that accepts anInt
. Its much more clear and concise. -
a_rahmanshah over 9 yearsString(varName) didn't work for me for NSIndexPath, but the above syntax worked.
-
ybakos over 9 yearsWhile this works, use the
toString
function, shown in an answer below. -
markhunte over 9 yearsI just watch some of the Stanford U new course on Swift and iOS 8. Your
var ss = "\(x)"
example is exactly how they advised converting a double to a string. Which I thought was easy and great. -
Ian Bradbury over 9 yearsAnd thinking more about sass - that's really bad.
-
Jehan about 9 yearsHow is this uglier than array literals?
-
Nilloc about 9 years
Int
doesn't appear to have atoString()
method at least not in Xcode 6.2 edit: I see that there is a globaltoString
method (notInt.toString()
), anyone know the advantage over using theString()
constructor? -
Teejay over 8 yearsNote that
String(Int?)
writes "Optional(Int)", at least in Swift 2, that could not be what you meant. Use insteadInt?.description
-
Maury Markowitz over 8 yearsPotentially stupid question, but should this be a function, or a computed variable? I can't recall which one Swift normally uses in these cases - is it
toInt
ortoInt()
. -
Jirson Tavera about 8 yearstoString has been renamed to String
-
Suragch over 7 years@jvarela, This does still work. I just retested it in Xcode 8.2 (Swift 3.0.2). The
String
initializer can take aUnicodeScalar
. -
Hardcore_Graverobber over 7 yearsThis worked for me when trying to show the value in a label. With the other approaches it was always Optional(0) instead of 0. Thank you
-
Omar Tariq about 7 yearsIn the last line of the code, why do we need an exclamation mark at the end?
-
Motti Shneor about 7 yearsWonderful, but doesn't work for me. I have an optional Int, and String(myInt) wont compile - it claims "Int? cannot be converted to String". There are no toString() or toInt() methods available for me either, or stringValue and intValue not there. Even a String(myInt!) will tell me that the initializer has been renamed to something like String(describing: myInt!).
-
Motti Shneor about 7 yearsWell the other ways are much uglier - now my only way is String(describing: myInt!). if that's not ugly... what is???
-
Motti Shneor about 7 yearss is now (Swift 3.1) String(describing: x) the older syntax yields compiler error.
-
caldera.sac about 7 years@OmarTariq, because we explicitly tells the compiler that the
integerValue
's type isInt
. then cannot have a nil value for it. so compiler tells you to unwrap it. if you want to avoid this , use it likelet integerValue = Int(stringValue)
. then you won't get a problem. sorry for the late reply. -
Rahul Sharma almost 7 yearsFrom API reference "Do not call this initializer directly. It is used by the compiler when interpreting string interpolations." May be you want to double check if you are using it somewhere.
-
nyg almost 7 yearsTo save yourself some time and hassle just use
myNumber.description
. No need for any extensions. -
Charlie Fish over 6 years@OmarTariq Unwrapping in this case can be really bad. If the string isn't a number this will crash your application. You should really check to ensure that is valid and not force unwrap it.
-
David Gay over 6 yearsFor Swift 4, see Hamed Gh's answer below. The correct usage is
String(describing: x)
-
Harshil Kotecha about 6 yearsresult Optional(1)
-
Eric Aya about 6 yearsNo.
String(describing:)
should never be used for anything else than debugging. It is not the normal String initializer. -
Eric Aya about 6 yearsThis is wrong.
String(describing:)
should never be used for anything else than debugging. It is not the normal String initializer. -
Eric Aya about 6 yearsThis is wrong.
String(describing:)
should never be used for anything else than debugging. It is not the normal String initializer. -
Harshil Kotecha about 6 yearsHello @Moritz so what can i do for remove optional word ? i have a Int value and than i want to print in label
-
Eric Aya about 6 yearsJust use the normal
String()
initializer. But don't give it an optional, unwrap first. Or, like in your example, use??
. Like this:let str = String(x ?? 0)
-
Harshil Kotecha about 6 yearsdeveloper.apple.com/documentation/swift/string/2427941-init i understand your point what is the use of describing
-
Eric Aya about 6 yearsIt's mostly for debugging purposes. You can describe the name of classes, get the description of instances, etc. But it should never be used for strings that are used in the app itself.
-
Eric Aya about 6 years@MottiShneor No, this is wrong.
String(describing:)
should never be used for anything else than debugging. It is not the normal String initializer. -
Hamed Ghadirian about 6 years@Moritz Could you provide a reference, please?
-
Hamed Ghadirian about 6 years@Harshil Its depends on your input 'x'
-
Harshil Kotecha about 6 yearsHamed Gh, Morithz already provide right answer in same question check my answer Just use the normal String() initializer. But don't give it an optional, unwrap first. Or, like in your example, use ??. Like this: let str = String(x ?? 0)
-
Eric Aya over 5 years@HamedGh Look at the examples in the link you give yourself. The
describing
method is here to... describe its content. It gives a description. Sometimes it's the same as the conversion, sometimes not. Give an optional todescribing
and you'll see the result... It will not be a conversion. There's a simple, dedicated way to convert: using the normal String initializer, as explained in other answers. Read the complete page that you link to: see that this method searches for descriptions using different ways, some of which would give wrong results if you expect accurate conversion.. -
Eric Aya over 5 years@HamedGh I'm not here to say you're wrong for the pleasure of doing it. But I care about an answer that is wrong and which gives wrong example to beginners and users. Having 20 upvotes on this means that at least 20 people now wrongly believe that
describing
is the correct way to convert, because of you. This is not ok. :( -
TimTwoToes over 5 yearsYou really should remove the describing part of this answer. Conversion should be done without using any parameter name in the String constructor.
-
Zonily Jame almost 5 yearsIs this still wrong in Swift 5? @ayaio, cause basing from documentation it doesn't seem wrong
-
Hamed Ghadirian over 4 years@TimTwoToes you should really mention your resource. As I quote "The String(describing:) initializer is the preferred way to convert an instance of any type to a string."