Reputation: 10738
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?
Upvotes: 21
Views: 22613
Reputation: 211
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))
}
}
Upvotes: 5
Reputation: 543
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) })
Upvotes: 41