{

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.

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.

THE BEST NEWSLETTER ANYWHERE
Join 6,000 subscribers and get a daily digest of full stack tutorials delivered to your inbox directly.No spam ever. Unsubscribe any time.

Similar Posts
Subscribe
You'll get a notification every time a post gets published here.