Xcode报错:Cannot convert value of type ‘String’ to expected argument type ‘String.Element’ (aka ‘Character’)
Xcode报错:Cannot convert value of type ‘String’ to expected argument type ‘String.Element’ (aka ‘Character’)

Xcode报错:Cannot convert value of type ‘String’ to expected argument type ‘String.Element’ (aka ‘Character’)

问题描述

在学习Swift UI字符串时,使用下面的代码查询单个单词在整个单词中的位置:

let word = "fangjunyu.com"
let tempWord = "y"
if let tempIndex = word.firstIndex(of: tempWord) {
    print(word.distance(from: word.startIndex, to: tempIndex))
}

但是Xcode提示该报错:

Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')

经查询发现问题出在String.firstIndex(of:)方法的参数需要传递一个Character类型,因此如果传递的是”y”,则可以正常查询,但这里传递的是常量tempWord。

在Swift中,双引号包含的文字默认被解释为String,即使是单个字符。

因此,解决方案就是在声明或者在传递给firtIndex(of:)方法时,将tempWord转换为Character类型。

解决方案

方案1

在声明时,将tempWord改为Character类型。

let word = "fangjunyu.com"
let tempWord: Character = "y"
if let tempIndex = word.firstIndex(of: tempWord) {
    print(word.distance(from: word.startIndex, to: tempIndex))
}

方案2

传递给firtIndex(of:)方法时,将tempWord转换为Character类型。

let word = "fangjunyu.com"
let tempWord = "y"
if let tempIndex = word.firstIndex(of: Character(tempWord)) {
    print(word.distance(from: word.startIndex, to: tempIndex))
}

以上两种方法均可解决该问题。

如果您认为这篇文章给您带来了帮助,您可以在此通过支付宝或者微信打赏网站开放者。

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注