592

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
Mike Chamberlain
  • 29,972
  • 27
  • 103
  • 151
Steve Marshall
  • 7,149
  • 4
  • 13
  • 17

23 Answers23

1020

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)
Bart van Kuik
  • 4,082
  • 1
  • 28
  • 50
Shai
  • 23,459
  • 7
  • 41
  • 65
  • 2
    While this works, use the `toString` function, shown in an answer below. – ybakos Jan 28 '15 at 22:20
  • 2
    `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? – Nilloc Apr 13 '15 at 01:58
  • Note that `String(Int?)` writes "Optional(Int)", at least in Swift 2, that could not be what you meant. Use instead `Int?.description` – Teejay Nov 16 '15 at 22:57
  • 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 Mar 09 '17 at 00:47
  • 9
    For Swift 4, see Hamed Gh's answer below. The correct usage is `String(describing: x)` – David Gay Feb 20 '18 at 17:23
93

Check the Below Answer:

let x : Int = 45
var stringValue = "\(x)"
print(stringValue)
Forge
  • 5,854
  • 6
  • 41
  • 58
PREMKUMAR
  • 8,097
  • 7
  • 26
  • 51
  • 47
    meh, this is an ugly and unnecessary workaround when `String` already has a constructor accepting `Int` – Gabriele Petronella Jun 11 '14 at 11:12
  • 3
    what wrong you find this? why you put down vote? @GabrielePetronella – PREMKUMAR Jun 11 '14 at 11:15
  • 2
    it's just a terrible way of achieving the desired result. The answer is technically correct, however, and for this reason I didn't downvote. – Gabriele Petronella Jun 11 '14 at 11:22
  • 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. – Desty Jun 12 '14 at 09:22
  • 1
    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. – Isuru Sep 15 '14 at 06:30
  • String(varName) didn't work for me for NSIndexPath, but the above syntax worked. – a_rahmanshah Nov 25 '14 at 13:57
  • How is this uglier than array literals? – Jehan Mar 02 '15 at 08:06
  • Well the other ways are much uglier - now my only way is String(describing: myInt!). if that's not ugly... what is??? – Motti Shneor Mar 09 '17 at 00:52
61

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.

Ian Bradbury
  • 1,286
  • 10
  • 17
54

In Swift 3.0:

var value: Int = 10
var string = String(describing: value)
vbgd
  • 1,819
  • 1
  • 9
  • 17
  • 10
    This is wrong. `String(describing:)` should never be used for anything else than debugging. It is not the normal String initializer. – Eric Aya Mar 31 '18 at 09:34
  • Is this still wrong in Swift 5? @ayaio, cause basing from documentation it doesn't seem wrong – Zonily Jame Jul 24 '19 at 02:26
27

Just for completeness, you can also use:

let x = 10.description

or any other value that supports a description.

Mike Lischke
  • 36,881
  • 12
  • 88
  • 141
27

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

Hamed Ghadirian
  • 5,491
  • 4
  • 40
  • 63
  • 3
    result Optional(1) – Harshil Kotecha Mar 31 '18 at 05:59
  • 15
    This is wrong. `String(describing:)` should never be used for anything else than debugging. It is not the normal String initializer. – Eric Aya Mar 31 '18 at 09:33
  • @Moritz Could you provide a reference, please? – Hamed Ghadirian Apr 29 '18 at 03:07
  • @Harshil Its depends on your input 'x' – Hamed Ghadirian Apr 29 '18 at 03:20
  • 3
    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) – Harshil Kotecha Apr 29 '18 at 04:54
  • 2
    @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 Aug 29 '18 at 13:42
  • @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. :( – Eric Aya Aug 29 '18 at 13:45
  • 2
    You really should remove the describing part of this answer. Conversion should be done without using any parameter name in the String constructor. – TimTwoToes Feb 18 '19 at 22:48
  • @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." – Hamed Ghadirian Sep 10 '19 at 11:46
11

Swift 4:

Trying to show the value in label without Optional() word.

here x is a Int value using.

let str:String = String(x ?? 0)
Harshil Kotecha
  • 2,518
  • 4
  • 24
  • 39
  • 4
    No. `String(describing:)` should never be used for anything else than debugging. It is not the normal String initializer. – Eric Aya Mar 31 '18 at 09:33
  • Hello @Moritz so what can i do for remove optional word ? i have a Int value and than i want to print in label – Harshil Kotecha Mar 31 '18 at 09:54
  • 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 Mar 31 '18 at 10:07
  • https://developer.apple.com/documentation/swift/string/2427941-init i understand your point what is the use of describing – Harshil Kotecha Mar 31 '18 at 11:03
  • 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 Mar 31 '18 at 11:05
8

To save yourself time and hassle in the future you can make an Int extension. Typically I create a shared code file where I put extensions, enums, and other fun stuff. Here is what the extension code looks like:

extension Int
{
    func toString() -> String
    {
        var myString = String(self)
        return myString
    }
}

Then later when you want to convert an int to a string you can just do something like:

var myNumber = 0
var myNumberAsString = myNumber.toString()
user2266987
  • 2,882
  • 1
  • 16
  • 4
  • 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()`. – Maury Markowitz Feb 10 '16 at 17:16
  • 1
    To save yourself some time and hassle just use `myNumber.description`. No need for any extensions. – nyg Aug 16 '17 at 09:44
8

in swift 3.0 this is how we can convert Int to String and String to Int

//convert Integer to String in Swift 3.0

let theIntegerValue :Int = 123  // this can be var also
let theStringValue :String = String(theIntegerValue)


//convert String to Integere in Swift 3.0


let stringValue : String = "123"
let integerValue : Int = Int(stringValue)!
Chanaka Anuradh Caldera
  • 4,280
  • 7
  • 34
  • 61
  • 1
    In the last line of the code, why do we need an exclamation mark at the end? – Omar Tariq Mar 03 '17 at 18:44
  • @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. – Chanaka Anuradh Caldera May 22 '17 at 09:10
  • 1
    @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. – Charlie Fish Jan 08 '18 at 03:11
7

for whatever reason the accepted answer did not work for me. I went with this approach:

var myInt:Int = 10
var myString:String = toString(myInt)
bkopp
  • 458
  • 1
  • 8
  • 20
5

Multiple ways to do this :

var str1:String="\(23)"
var str2:String=String(format:"%d",234)
Dhruv Ramani
  • 2,536
  • 2
  • 19
  • 29
4

Swift 2:

var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)
durron597
  • 30,764
  • 16
  • 92
  • 150
2

iam using this simple approach

String to Int:

 var a = Int()
var string1 = String("1")
a = string1.toInt()

and from Int to String:

var a = Int()
a = 1
var string1 = String()
 string1= "\(a)"
2

Convert Unicode Int to String

For those who want to convert an Int to a Unicode string, you can do the following:

let myInteger: Int = 97

// convert Int to a valid UnicodeScalar
guard let myUnicodeScalar = UnicodeScalar(myInteger) else {
    return ""
}

// convert UnicodeScalar to String
let myString = String(myUnicodeScalar)

// results
print(myString) // a

Or alternatively:

let myInteger: Int = 97
if let myUnicodeScalar = UnicodeScalar(myInteger) {
    let myString = String(myUnicodeScalar)
}
Community
  • 1
  • 1
Suragch
  • 364,799
  • 232
  • 1,155
  • 1,198
  • @jvarela, This does still work. I just retested it in Xcode 8.2 (Swift 3.0.2). The `String` initializer can take a `UnicodeScalar`. – Suragch Jan 02 '17 at 05:17
1

exampleLabel.text = String(yourInt)

Michael
  • 8,464
  • 2
  • 59
  • 62
1

I prefer using String Interpolation

let x = 45
let string = "\(x)"

Each object has some string representation. This makes things simpler. For example if you need to create some String with multiple values. You can also do any math in it or use some conditions

let text = "\(count) \(count > 1 ? "items" : "item") in the cart. Sum: $\(sum + shippingPrice)"
Robert Dresler
  • 10,121
  • 2
  • 15
  • 35
0

To convert String into Int

var numberA = Int("10")

Print(numberA) // It will print 10

To covert Int into String

var numberA = 10

1st way)

print("numberA is \(numberA)") // It will print 10

2nd way)

var strSomeNumber = String(numberA)

or

var strSomeNumber = "\(numberA)"
Anil Kukadeja
  • 1,256
  • 1
  • 14
  • 26
0

In swift 3.0, you may change integer to string as given below

let a:String = String(stringInterpolationSegment: 15)

Another way is

let number: Int = 15
let _numberInStringFormate: String = String(number)

//or any integer number in place of 15

Dilip Jangid
  • 636
  • 10
  • 20
  • 1
    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. – Rahul Sharma Jun 01 '17 at 17:37
0
let a =123456888
var str = String(a)

OR

var str = a as! String
FelixSFD
  • 5,456
  • 10
  • 40
  • 106
Amul4608
  • 1,232
  • 12
  • 25
0

If you like swift extension, you can add following code

extension Int
{
    var string:String {
        get {
            return String(self)
        }
    }
}

then, you can get string by the method you just added

var x = 1234
var s = x.string
Lai Lee
  • 484
  • 7
  • 11
0

A little bit about performance UI Testing Bundle on iPhone 7(real device) with iOS 14

let i = 0
lt result1 = String(i) //0.56s 5890kB
lt result2 = "\(i)" //0.624s 5900kB
lt result3 = i.description //0.758s 5890kB
import XCTest

class ConvertIntToStringTests: XCTestCase {

    let count = 1_000_000
    
    func measureFunction(_ block: () -> Void) {
        
        let metrics: [XCTMetric] = [
            XCTClockMetric(),
            XCTMemoryMetric()
        ]
        let measureOptions = XCTMeasureOptions.default
        measureOptions.iterationCount = 5
        
        measure(metrics: metrics, options: measureOptions) {
            block()
        }
    }

    func testIntToStringConstructor() {
        var result = ""
        
        measureFunction {
            
            for i in 0...count {
                result += String(i)
            }
        }

    }
    
    func testIntToStringInterpolation() {
        var result = ""
        
        measureFunction {
            for i in 0...count {
                result += "\(i)"
            }
        }
    }
    
    func testIntToStringDescription() {
        var result = ""
        measureFunction {
            for i in 0...count {
                result += i.description
            }
        }
    }
}
yoAlex5
  • 13,571
  • 5
  • 105
  • 98
-1
let Str = "12"
let num: Int = 0
num = Int (str)
mmgross
  • 2,776
  • 1
  • 21
  • 32
-1
let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45
Roi Zakai
  • 124
  • 3