Swift – Convert String to Int Swift
Swift provides a number of ways to convert a string value into an integer value. Though, we can convert a numeric string only into an integer value. In this article, we will see the two most common methods used to convert a string to an integer value. A string is a collection of characters. Swift provides String data type with the help of which we can store a string. For example, “GeeksforGeeks”, “GFG”, etc. A variable can be declared as String type by following the below syntax,
Syntax:
let myVariable: String
For example: myVariable = “GeeksforGeeks”
Using Int initializer
Swift provides the function of integer initializers using which we can convert a string into an Int type. To handle non-numeric strings, we can use nil coalescing using which the integer initializer returns an optional integer.
let myStringVariable = “25”
let myIntegerVariable = Int(myStringVariable) ?? 0
It means that if the string is non-numeric then assign the variable with 0 otherwise convert the numeric string to an integer. Below is the implementation to convert a String into Int:
Example:
Swift
let myStringVariable = "25"
let myIntegerVariable = Int (myStringVariable) ?? 0
print ( "Integer Value:" , myIntegerVariable)
let myStringvariable = "GeeksforGeeks"
let myIntegervariable = Int (myStringvariable) ?? 0
print ( "Integer Value:" , myIntegervariable)
|
Output:
Integer Value: 25
Integer Value: 0
Using NSString
NSString in Swift is a class that is used to create objects that lie in heap and they are passed by reference. It provides different types of methods for comparing, searching, and modifying strings. We can convert a numeric string into an integer value indirectly. Firstly, we can convert a string into an NSString then we can use “integerValue” property used with NSStrings to convert an NSString into an integer value.
Example:
In the below program we have converted the numeric string into NSString then we have applied “integerValue” property to convert a string into an integer value.
Swift
import Foundation
import Glibc
let myString = "25"
let myIntegerVariable = (myString as NSString) .integerValue
print ( "Integer Value:" , myString)
|
Output:
Integer Value: 25
Last Updated :
07 Jan, 2022
Like Article
Save Article
Share your thoughts in the comments
Please Login to comment...