I'm trying to get letters only from String in Swift.
For example:
let str = "he4ll5663#$#0o"
print(str.letters) // prints hello
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.
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