I am having troubles while converting optional string to int.
println("str_VAR = \(str_VAR)")
println(str_VAR.toInt())
Result is
str_VAR = Optional(100)
nil
And i want it to be
str_VAR = Optional(100)
100
Using NSString 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.
The getAsInt() method is used to get the integer value present in an OptionalInt object. If the OptionalInt object doesn't have a value, then NoSuchElementException is thrown.
An if statement is the most common way to unwrap optionals through optional binding. We can do this by using the let keyword immediately after the if keyword, and following that with the name of the constant to which we want to assign the wrapped value extracted from the optional. Here is a simple example.
// Swift program to convert an optional string // into the normal string import Swift; var str:String=""; print("Enter String:"); str = readLine()!; print("String is: ",str); Output: Enter String: Hello World String is: Hello World ... Program finished with exit code 0 Press ENTER to exit console.
At the time of writing, the other answers on this page used old Swift syntax. This is an update.
String? -> Int
let optionalString: String? = "100"
if let string = optionalString, let myInt = Int(string) {
print("Int : \(myInt)")
}
This converts the string "100"
into the integer 100
and prints the output. If optionalString
were nil
, hello
, or 3.5
, nothing would be printed.
Also consider using a guard
statement.
Try this:
if let i = str_VAR?.toInt() {
println("\(i)")
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With