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.

Custom String Convertible

enter image description here

Share:
646,007
Steve Marshall
Author by

Steve Marshall

Fledgling programmer, living in Brighton, UK. Trying to figure out iOS.

Updated on July 15, 2022

Comments

  • Steve Marshall
    Steve Marshall almost 2 years

    I'm trying to work out how to cast an Int into a String 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
    Gabriele Petronella almost 10 years
    meh, this is an ugly and unnecessary workaround when String already has a constructor accepting Int
  • PREMKUMAR
    PREMKUMAR almost 10 years
    what wrong you find this? why you put down vote? @GabrielePetronella
  • Desty
    Desty almost 10 years
    I 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
    Isuru over 9 years
    I 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 an Int. Its much more clear and concise.
  • a_rahmanshah
    a_rahmanshah over 9 years
    String(varName) didn't work for me for NSIndexPath, but the above syntax worked.
  • ybakos
    ybakos over 9 years
    While this works, use the toString function, shown in an answer below.
  • markhunte
    markhunte over 9 years
    I 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
    Ian Bradbury over 9 years
    And thinking more about sass - that's really bad.
  • Jehan
    Jehan about 9 years
    How is this uglier than array literals?
  • Nilloc
    Nilloc about 9 years
    Int doesn't appear to have a toString() method at least not in Xcode 6.2 edit: I see that there is a global toString method (not Int.toString()), anyone know the advantage over using the String() constructor?
  • Teejay
    Teejay over 8 years
    Note that String(Int?) writes "Optional(Int)", at least in Swift 2, that could not be what you meant. Use instead Int?.description
  • Maury Markowitz
    Maury Markowitz over 8 years
    Potentially 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 or toInt().
  • Jirson Tavera
    Jirson Tavera about 8 years
    toString has been renamed to String
  • Suragch
    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 a UnicodeScalar.
  • Hardcore_Graverobber
    Hardcore_Graverobber over 7 years
    This 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
    Omar Tariq about 7 years
    In the last line of the code, why do we need an exclamation mark at the end?
  • Motti Shneor
    Motti Shneor about 7 years
    Wonderful, 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
    Motti Shneor about 7 years
    Well the other ways are much uglier - now my only way is String(describing: myInt!). if that's not ugly... what is???
  • Motti Shneor
    Motti Shneor about 7 years
    s is now (Swift 3.1) String(describing: x) the older syntax yields compiler error.
  • caldera.sac
    caldera.sac about 7 years
    @OmarTariq, because we explicitly tells the compiler that the integerValue's type is Int. then cannot have a nil value for it. so compiler tells you to unwrap it. if you want to avoid this , use it like let integerValue = Int(stringValue). then you won't get a problem. sorry for the late reply.
  • Rahul Sharma
    Rahul Sharma almost 7 years
    From 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
    nyg almost 7 years
    To save yourself some time and hassle just use myNumber.description. No need for any extensions.
  • Charlie Fish
    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
    David Gay over 6 years
    For Swift 4, see Hamed Gh's answer below. The correct usage is String(describing: x)
  • Harshil Kotecha
    Harshil Kotecha about 6 years
    result Optional(1)
  • Eric Aya
    Eric Aya about 6 years
    No. String(describing:) should never be used for anything else than debugging. It is not the normal String initializer.
  • Eric Aya
    Eric Aya about 6 years
    This is wrong. String(describing:) should never be used for anything else than debugging. It is not the normal String initializer.
  • Eric Aya
    Eric Aya about 6 years
    This is wrong. String(describing:) should never be used for anything else than debugging. It is not the normal String initializer.
  • Harshil Kotecha
    Harshil Kotecha about 6 years
    Hello @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
    Eric Aya about 6 years
    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)
  • Harshil Kotecha
    Harshil Kotecha about 6 years
    developer.apple.com/documentation/swift/string/2427941-init i understand your point what is the use of describing
  • Eric Aya
    Eric Aya about 6 years
    It'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
    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
    Hamed Ghadirian about 6 years
    @Moritz Could you provide a reference, please?
  • Hamed Ghadirian
    Hamed Ghadirian about 6 years
    @Harshil Its depends on your input 'x'
  • Harshil Kotecha
    Harshil Kotecha about 6 years
    Hamed 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
    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 to describing 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
    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
    TimTwoToes over 5 years
    You really should remove the describing part of this answer. Conversion should be done without using any parameter name in the String constructor.
  • Zonily Jame
    Zonily Jame almost 5 years
    Is this still wrong in Swift 5? @ayaio, cause basing from documentation it doesn't seem wrong
  • Hamed Ghadirian
    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."