Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Swift - Get letters only from String

Tags:

swift

I'm trying to get letters only from String in Swift.

For example:

let str = "he4ll5663#$#0o"
print(str.letters) // prints hello
like image 516
Gal Shahar Avatar asked Feb 13 '26 03:02

Gal Shahar


1 Answers

Here is a way to do it using filter on the unicodeScalars of the String:

extension String {
    var letters: String {
        return String(unicodeScalars.filter(CharacterSet.letters.contains))
    }
}

let str = "he4ll5663#$#0o"
print(str.letters)  // hello

Thanks @MartinR for the suggestion to avoid using first! (in my original answer) by changing the filter to the unicodeScalars of the String.

like image 195
vacawama Avatar answered Feb 15 '26 18:02

vacawama



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!