Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Simplest way to convert an optional String to an optional Int in Swift

Tags:

swift

optional

It seems to me there ought to be a simple way to do an optional conversion from a String to an Int in Swift but I can't figure it out.

value is a String? and I need to return an Int?.

Basically I want to do this, but without the boilerplate:

return value != nil ? Int(value) : nil

I tried this, which seems to fit with Swift's conventions and would be nice and concise, but it doesn't recognize the syntax:

return Int?(value)
like image 260
devios1 Avatar asked Jun 19 '17 14:06

devios1


People also ask

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

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 convert a string to int in Swiftui?

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.


2 Answers

You can use the nil coalescing operator ?? to unwrap the String? and use a default value "" that you know will produce nil:

return Int(value ?? "")

Another approach: Int initializer that takes String?

From the comments:

It's very odd to me that the initializer would not accept an optional and would just return nil if any nil were passed in.

You can create your own initializer for Int that does just that:

extension Int {
    init?(_ value: String?) {
        guard let value = value else { return nil }
        self.init(value)
    }
}

and now you can just do:

var value: String?
return Int(value)
like image 147
vacawama Avatar answered Oct 04 '22 14:10

vacawama


You can use the flatMap() method of Optional:

func foo(_ value: String?) -> Int? {
    return value.flatMap { Int($0) }
}

If value == nil then flatMap returns nil. Otherwise it evaluates Int($0) where $0 is the unwrapped value, and returns the result (which can be nil if the conversion fails):

print(foo(nil) as Any)      // nil
print(foo("123") as Any)    // Optional(123)
print(foo("xyz") as Any)    // nil
like image 30
Martin R Avatar answered Oct 04 '22 14:10

Martin R