How to filter characters from a string in Swift 4

Viewed 17159

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?

2 Answers

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) })

Easiest:

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))
    }
}
Related