Swift 4中字符串转字符报错:无法将String转为Character求助
解决Swift 4中String与Character类型不匹配的问题
错误原因分析
你遇到的两个报错本质都是类型不匹配:
- 第一个错误:
theWordArray.index(of: "\(selectedLetter)")
你的theWordArray应该是[Character]类型的数组(存储单个字符),但"\(selectedLetter)"生成的是String类型,index(of:)方法需要传入和数组元素同类型的参数,所以无法转换。 - 第二个错误:
var selectedChar:Character = selectedLetterselectedLetter是可选类型String?,既没有安全解包可选值,也没有把String转换成Character,直接赋值自然会报错。
修复方案
我们用安全解包+类型转换的方式来解决,同时避免强制解包(!)带来的崩溃风险:
// 先安全解包可选的selectedLetter,再提取对应的Character if let selectedLetter = selectedLetter, let selectedChar = selectedLetter.first { // 检查字符是否在removedLetters中 if removedLetters.contains(selectedChar) { print("\(selectedLetter) is in the word") // 获取数组中字符的索引,同时处理找不到的情况 if let index = theWordArray.index(of: selectedChar) { print("Index of \(selectedChar): \(index)") } else { print("\(selectedChar) wasn't found in the word array") } } }
关键细节说明
- 用
if let selectedLetter = selectedLetter安全解包可选值,避免强制解包!导致的崩溃; - 用
selectedLetter.first把单个字符的String转换成Character(如果你的selectedLetter是多字符的String,这里需要根据需求调整,但从上下文看应该是单个字符); - 调用
theWordArray.index(of:)时传入Character类型的selectedChar,和数组元素类型匹配,就不会报错了。
内容的提问来源于stack exchange,提问作者dhyman
相关产品推荐
相关产品推荐

