我已經看到這個問題的其他答案,但我只是想以不同的方式做。然而無論我做什麼,我都不能讓我的類型匹配。如何編寫函數來評估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' –