How to Convert String to Int in swift with example

This article talks about three ways to convert String to Int or String to Int in Swift Language.

  • Convert String to number in Swift

    • Use the Int constructor.
  • Convert number to String in swift

    • String constructor
    • String interpolation syntax
    • double description

String and Int are different data types and hold different values.

When we want to perform mathematical calculations on strings that contain numbers, we must convert string to int.

If a user enters a numeric value in the text box of a web application form, this will be received as input as a string.

For example, a string contains the numbers 134 and needs this value to convert to int.

The string is a primitive type that contains a group of characters enclosed in double quotes

int is a primitive type that contains numeric values.

How to convert String to int in Swift

There are multiple ways we can convert String to int

  • Use the Int constructor.

Pass a string to the Int constructor and returns the Int value.

var str = "11"
let number: Int? = Int(str)


print(type(of: number)) // Int
print(type(of: str)) // String

How to convert int to String in Swift

There are multiple ways we can convert an Int to a String

  • use String constructor

    The string contains constructor that takes an integer number and returns the string

var number: Int = 5
var string = String( number)
print(type(of: number)) // Int
print(type(of: string)) // String
  • use interpolation syntax

String interpolation with number returns the string.

var number: Int = 5
var string = "\(number)"

print(type(of: number)) // Int
print(type(of: string)) // String
  • Description property

Description property of Int returns String.

var number: Int = 5
var str=number.description

print(type(of: number)) // Int
print(type(of: str)) // String

Conclusion

To summarize, different ways we can convert String into Int and Int to String in Swift example.