[string] Convert Int to String in Swift

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

This question is related to string casting int converter swift

The answer is


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

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)

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


Multiple ways to do this :

var str1:String="\(23)"
var str2:String=String(format:"%d",234)

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()

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.


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)!

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)

In Swift 3.0:

var value: Int = 10
var string = String(describing: value)

Swift 2:

var num1 = 4
var numString = "56"
var sum2 = String(num1) + numString
var sum3 = Int(numString)

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)"

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)"

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

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)"

let a =123456888
var str = String(a)

OR

var str = a as! String

let intAsString = 45.description     // "45"
let stringAsInt = Int("45")          // 45

let Str = "12"
let num: Int = 0
num = Int (str)

Check the Below Answer:

let x : Int = 45
var stringValue = "\(x)"
print(stringValue)

Just for completeness, you can also use:

let x = 10.description

or any other value that supports a description.


exampleLabel.text = String(yourInt)


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)
}

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


Examples related to string

How to split a string in two and store it in a field String method cannot be found in a main class method Kotlin - How to correctly concatenate a String Replacing a character from a certain index Remove quotes from String in Python Detect whether a Python string is a number or a letter How does String substring work in Swift How does String.Index work in Swift swift 3.0 Data to String? How to parse JSON string in Typescript

Examples related to casting

Subtracting 1 day from a timestamp date Cast object to interface in TypeScript TypeScript enum to object array Casting a number to a string in TypeScript Hive cast string to date dd-MM-yyyy Casting int to bool in C/C++ Swift double to string No function matches the given name and argument types C convert floating point to int PostgreSQL : cast string to date DD/MM/YYYY

Examples related to int

How can I convert a char to int in Java? How to take the nth digit of a number in python "OverflowError: Python int too large to convert to C long" on windows but not mac Pandas: Subtracting two date columns and the result being an integer Convert bytes to int? How to round a Double to the nearest Int in swift? Leading zeros for Int in Swift C convert floating point to int Convert Int to String in Swift Converting String to Int with Swift

Examples related to converter

No converter found capable of converting from type to type How to convert datetime to integer in python Convert Int to String in Swift Concatenating elements in an array to a string Decimal to Hexadecimal Converter in Java Calendar date to yyyy-MM-dd format in java ffmpeg - Converting MOV files to MP4 Java: How to convert String[] to List or Set Convert xlsx to csv in Linux with command line How to convert string to long

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?