1

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)
R21
  • 396
  • 2
  • 12
  • 2
    Possible duplicate of http://stackoverflow.com/questions/24502669/swift-how-to-find-out-if-letter-is-alphanumeric-or-digit. – Martin R May 29 '15 at 21:39

3 Answers3

2

Xcode 8 beta4 • Swift 3

extension String {
    var lettersOnly: String {
        return components(separatedBy: CharacterSet.letters.inverted).joined(separator:"")
    }
    var lettersArray: [Character] {
        return Array(lettersOnly.characters)
    }
}

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"]
Leo Dabus
  • 229,809
  • 59
  • 489
  • 571
2

Why not just:

let alphabet: [Character] = [
  "a", "b", "c", "d", "e", "f", "g", "h", "i", "j", "k", "l", "m",
  "n", "o", "p", "q", "r", "s", "t", "u", "v", "w", "x", "y", "z"
]

let word = "h4e7l2l8o1"

var answer = [String]()

for letter in word {
  if contains(alphabet, letter) {
    answer.append(String(letter))
  }
}

"".join(answer) // "hello"

or even:

let answer = "".join(filter(word) {contains(alphabet, $0)}.map{String($0)}) // "hello"
oisdk
  • 9,763
  • 4
  • 18
  • 36
1

This should work:

import Foundation // For playground or REPL

let word = "This is a string !#€%!€#% 123456 åäö é 中國"
let letterCharSet = NSCharacterSet.letterCharacterSet().invertedSet
let newWord = "".join(word.componentsSeparatedByCharactersInSet(letterCharSet))
// Outputs: "Thisisastringåäöé中國"
Mikael Hellman
  • 2,664
  • 14
  • 22