swift - 为什么 string.contains ("text") 不适用于 swift 5 中的字符串?

标签 swift string contains

let string = "hello Swift"
if string.contains("Swift") {
    print("exists")
}

无法将“String”类型的值转换为预期的参数类型“String.Element”(又名“Character”)

为什么版本 5 会出现这样的错误,我该怎么办?

最佳答案

当您使用 contains() 并向其传递一个 String 时,Swift 会尝试使用该函数的重载,该函数接受某种字符串,例如 contains( _ other: StringProtocol) 不是纯 Swift String 一部分的函数。相反,它会找到 contains(_ element: Character) 并且它不能接受 String 作为参数并且只接受 'String.Element'(又名 'Character')。引用contains

您正在寻找的函数是在一个协议(protocol)中定义的,String 符合它,称为 StringProtocol,它位于 Foundation 中。

因此,如果您需要它,请确保您导入 Foundation 或更高级别的框架,如 UIKit

关于swift - 为什么 string.contains ("text") 不适用于 swift 5 中的字符串?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57316831/

相关文章:

ios - 从另一个 View Controller 访问数组数据

swift - 通过 AVfoundation 保存音频时出错

ios - Swift 编译器错误 : Missing required modules;

Java String 过滤掉不需要的字符

matlab - 从matlab中的字符串中提取前4个字母

swift - fatal error : Index out of range - Swift 4 and Firebase

iPhone NSURLConnection : connectionDidFinishLoading - how to return a string to the calling method

c# - 我可以将嵌入式 lambda 与 Contains 方法一起使用吗?

c# - DataSet 是否具有 Contain 或 In 功能?

Java:包含()方法