【发布时间】:2017-03-21 20:40:39
【问题描述】:
我已经看到了这个问题的其他答案,但我只是想以不同的方式来做。然而,无论我做什么,我都无法让我的类型匹配。
func ContainsOnlyAlphabets(_ word : String) -> Bool{
let letters = CharacterSet.letters // Set<Character>
let trimmed = word.trimmingCharacters(in: .whitespaces)
let characterViewArray = Array(trimmed.characters) // Array<characterView>
let characterArray = characterViewArray.map{Character($0)} // Error: Can't create Chars
let wordCharactersSet = Set(characterArray) // Set<Character>
let intersection = wordCharactersSet.intersection(letters)
return intersection.count == characterArray.count
}
我必须进行所有的 Set、Char、String、Array 转换,但仍然无法正确处理 :(.
无法使用参数列表调用类型“Character”的初始化程序 '((String.CharacterView._Element))' 类型的
【问题讨论】:
-
if trimmed.rangeOfCharacter(from: letters.inverted) == nil呢? -
注意
CharacterSet和Set<Character>是不同的类型,所以你的计算wordCharactersSet.intersection(letters)的方法不能工作。 -
一条线解决方案
return word.trimmingCharacters(in: .whitespaces).rangeOfCharacter(from: CharacterSet.letters.inverted) == nil
标签: swift string set character characterview