In the following Swift 3 code I'm extracting all numbers from a string but I can not figure out how to do the same thing in Swift 4.
var myString = "ABC26FS464"
let myNumbers = String(myString.characters.filter { "01234567890".characters.contains($0)})
print(myNumbers) // outputs 26464
How can I extract all numbers from a string in Swift 4?
To filter strings in a Swift String Array based on length, call filter() method on this String Array, and pass the condition prepared with the string length as argument to the filter() method. filter() method returns an array with only those elements that satisfy the given predicate/condition.
In the Swift string, we check the removal of a character from the string. To do this task we use the remove() function. This function is used to remove a character from the string. It will return a character that was removed from the given string.
In this tutorial, we will learn about the Swift String removeAll() method with the help of examples. The removeAll() method removes all the elements from the string based on a given condition.
The dropFirst() method removes the first character of the string.
As "Character" has almost all the most used character checking with ".isXY" computed properties, you can use this pattern, which seems to be the most convenient and Swifty way to do string filtering.
/// Line by line explanation.
let str = "Stri1ng wi2th 3numb4ers".filter(\.isNumber) // "1234"
let int = Int(str) // Optional<Int>(1234)
let unwrappedInt = int! // 1234
/// Solution.
extension String {
/// Numbers in the string as Int.
///
/// If doesn't have any numbers, then 0.
var numbers: Int {
Int(filter(\.isNumber)) ?? 0
}
/// Numbers in the string as Int.
///
/// If doesn't have any numbers, then nil.
var optionalNumbers: Int? {
Int(filter(\.isNumber))
}
}
Swift 4 makes it a little simpler. Just remove the .characters and use
let myNumbers = myString.filter { "0123456789".contains($0) }
But to really do it properly, you might use the decimalDigits character set...
let digitSet = CharacterSet.decimalDigits
let myNumbers = String(myString.unicodeScalars.filter { digitSet.contains($0) })
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