我已经看到这个问题的其他答案,但我只是想以不同的方式做。然而无论我做什么,我都不能让我的类型匹配。如何编写函数来评估String是否只有字符?
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
}
我不得不做的所有设置,字符,字符串数组转换,但仍无法得到它的权利:(。
不能调用类型“字符”初始化与参数列表类型的 '((String.CharacterView._Element))'
怎么样'如果trimmed.rangeOfCharacter(from:letters.inverted)== nil'? –
请注意'CharacterSet'和'Set'是不同的类型,所以计算'wordCharactersSet.intersection(letters)'的方法不能工作。 –
单行解决方案'return word.trimmingCharacters(in:.whitespaces).rangeOfCharacter(from:CharacterSet.letters。倒数)== nil' –