I need to extract numbers from string and put them into a new array in Swift.
var str = "I have to buy 3 apples, 7 bananas, 10eggs"
I tried to loop each characters and I have no idea to compare between Characters and Int.
In Python an strings can be converted into a integer using the built-in int() function. The int() function takes in any python data type and converts it into a integer.
swift1min read To convert a float value to an Int, we can use the Int() constructor by passing a float value to it. Note: When we use this conversion the Integer is always rounded to the nearest downward value, like 12.752 to 12 or 6.99 to 6 .
To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .
Swift 3/4
let string = "0kaksd020dk2kfj2123" if let number = Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) { // Do something with this number }
You can also make an extension like:
extension Int { static func parse(from string: String) -> Int? { return Int(string.components(separatedBy: CharacterSet.decimalDigits.inverted).joined()) } }
And then later use it like:
if let number = Int.parse(from: "0kaksd020dk2kfj2123") { // Do something with this number }
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