Filter non-digits from string

Swift 3 & 4

extension String {
    var digits: String {
        return components(separatedBy: CharacterSet.decimalDigits.inverted)
            .joined()
    }
}

Swift 5

You should be able to omit return

Also: Read the comment from @onmyway133 for a word of caution


Split the string by non-digit characters to an array of digits and the join them back to a string:

Swift 1:

let stringArray = origString.componentsSeparatedByCharactersInSet(
    NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = NSArray(array: stringArray).componentsJoinedByString("")

Swift 2:

let stringArray = origString.componentsSeparatedByCharactersInSet(
    NSCharacterSet.decimalDigitCharacterSet().invertedSet)
let newString = stringArray.joinWithSeparator("")

Swift 3 & 4:

let newString = origString
    .components(separatedBy:CharacterSet.decimalDigits.inverted)
    .joined()