Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert optional string to int in Swift

Tags:

swift

optional

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
like image 376
moonvader Avatar asked Jul 29 '15 08:07

moonvader


People also ask

How do I convert a string to an int in Swift?

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.

How do you change from optional to INT?

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.

How do I unwrap optional in Swift?

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.

How do I change a string from optional to string in Swift?

// 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.


2 Answers

At the time of writing, the other answers on this page used old Swift syntax. This is an update.

Convert Optional String to Int: 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.

like image 53
Suragch Avatar answered Oct 04 '22 19:10

Suragch


Try this:

if let i = str_VAR?.toInt() {
    println("\(i)")
}
like image 26
Greg Avatar answered Oct 04 '22 19:10

Greg