Simplest way to convert optional string to optional Int in Swift

It seems to me that there should be an easy way to do an optional conversion from String to Int to Swift, but I can't figure it out.

value is a String? and i need to return Int? .

Basically, I want to do this, but without a template:

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

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

 return Int?(value) 
+5
source share
3 answers

Can you use nil coalescing operator ?? to expand String? and use the default value "" , which, as you know, will result in nil :

 return Int(value ?? "") 

Another approach: an int initializer that takes a String?

From the comments:

It is very strange to me that the initializer did not agree with the optional and would simply return nil if any of them were passed.

You can create your own initializer for Int , which 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) 
+5
source

You can use the flatMap() Optional method:

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

If value == nil , then flatMap returns nil . Otherwise, evaluates Int($0) , where $0 is the expanded value, and returns the result (which may 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 
+8
source

With the String extension, don't worry about string == nil

 extension String { func toInt() -> Int? { return Int(self) } } 

Using:

 var nilString: String? print("".toInt()) // nil print(nilString?.toInt()) // nil print("123".toInt()) // Optional(123) 
+2
source

Source: https://habr.com/ru/post/1268989/


All Articles