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