R21 R21 - 4 months ago 21
Python Question

Is there a function that checks if a character in a string is a letter in the alphabet? (Swift)

I'm converting a python programme into swift, and one section uses a for loop to keep every character within a string if it is a letter. In python, it's as simple as using '.isalpha()', is there anything in swift that does this? Code in python:

word = 'hello 123'
new_word = []
for i in word:
if i.isalpha():
new_word.append(i)

Answer

Xcode 7.3.1 • Swift 2.2.1

extension String {
    var lettersOnly: String {
        return componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet).joinWithSeparator("")
    }
    var lettersArray: [Character] {
        return Array(lettersOnly.characters)
    }
}

Swift 1.x

import UIKit

extension String {

    var lettersOnly: String {
        return "".join(componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet))
    }
    var lettersArray: [Character] {
        return Array("".join(componentsSeparatedByCharactersInSet(NSCharacterSet.letterCharacterSet().invertedSet)))
    }


}
let word = "hello 123"

let letters = word.lettersOnly        // "hello"

let lettersArray = word.lettersArray  // ["h", "e", "l", "l", "o"]