by Sai gowtham

How to convert a given string to int in Swift

We can convert a string to an int in swift by using the built-in Int() initializer syntax by passing the string as an argument to it.

In this example, we are converting the string "929" to an int value 929:

let str = "929"

let convertedNumber = Int(str) ?? 0

print(convertedNumber)

Output:

929

In the above code, we have added the Int(str) ?? 0 it means the Int() returns an optional value 0 if it fails to convert the given string into an int.

Top Udemy Courses

JavaScript - The Complete Guide 2020 (Beginner + Advanced)
JavaScript - The Complete Guide 2020 (Beginner + Advanced)
45,614 students enrolled
52 hours of video content
View Course
React - The Complete Guide (incl Hooks, React Router, Redux)
React - The Complete Guide (incl Hooks, React Router, Redux)
284,472 students enrolled
40 hours of video content
View Course
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
Vue JS 2 - The Complete Guide (incl. Vue Router & Vuex)
130,921 students enrolled
21 hours of video content
View Course