参见英文答案 >
What is the best way to determine if a string contains a character from a set in Swift7个
我试图检查一个特定的字符串是否包含字母.
@H_403_15@
您可以通过以下方式使用NSCharacterSet:
我试图检查一个特定的字符串是否包含字母.
到目前为止,我已经看到了NSCharacterSet.letterCharacterSet()作为一组字母,但我无法检查该集合中的一个字符是否在给定的字符串中.当我使用这个代码时,我收到一个错误:
‘Character’ is not convertible to ‘unichar’
对于以下代码:
for chr in input{ if letterSet.characterIsMember(chr){ return "Woah,chill out!" } }
let letters = NSCharacterSet.letterCharacterSet() let phrase = "Test case" let range = phrase.rangeOfCharacterFromSet(letters) // range will be nil if no letters is found if let test = range { println("letters found") } else { println("letters not found") }
或者你也可以这样做:
func containsOnlyLetters(input: String) -> Bool { for chr in input { if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) { return false } } return true }
In Swift 2:
func containsOnlyLetters(input: String) -> Bool { for chr in input.characters { if (!(chr >= "a" && chr <= "z") && !(chr >= "A" && chr <= "Z") ) { return false } } return true }
这取决于你,选择一种方式.我希望这能帮助你.