[英]Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character') when trying to filter array data
I'm trying to "search" item from an array and if the item contains searchkey, it should appended the data to filteredArray.我正在尝试从数组中“搜索”项目,如果该项目包含搜索键,则应将数据附加到filteredArray。 But when i'm trying to check if the data contains search key it showed an error "Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')"
但是当我试图检查数据是否包含搜索键时,它显示了一个错误“无法将类型'字符串'的值转换为预期的参数类型'String.Element'(又名'字符')”
Example: let data: [String] = ["Apples", "Apricots", "Bananas", "Cherries", "Grapefruit", "Grapes"] searchKey: "ap" should filter "Apples" and "Appricots".示例:let data: [String] = ["Apples", "Apricots", "Bananas", "Cherries", "Grapefruit", "Grapes"] searchKey: "ap" 应该过滤“Apples”和“Appricots”。 searcKey: "gr" should filter "Grapefruit" and "Grapes".
searcKey: "gr" 应该过滤 "Grapefruit" 和 "Grapes"。
My code:我的代码:
let data: [String] = ["Apples", "Apricots", "Bananas", "Cherries", "Grapefruit", "Grapes"]
var filteredData: [String] = []
let searchKey: String = "Ap"
for item in data {
if item.contains(searchKey) {
filteredData.append(item)
}
}
Swift String contains(_:) accepts Character
as parameter, instead of String
: Swift String contains(_:)接受
Character
作为参数,而不是String
:
func contains(_ element: Character) -> Bool
You can use Generic Instance Method contains(_:) from Foundation
:您可以使用来自
Foundation
通用实例方法contains(_:) :
func contains<T>(_ other: T) -> Bool where T : StringProtocol
Just by importing Foundation
and it should work.只需导入
Foundation
就可以了。
Seems your code works properly.似乎您的代码工作正常。 You may need to import Foundation.
您可能需要导入 Foundation。 Also, there is a shorter way to filter your data:
此外,还有一种更短的方法来过滤您的数据:
let data: [String] = ["Apples", "Apricots", "Bananas", "Cherries", "Grapefruit", "Grapes"]
var filteredData: [String] = []
filteredData = data.filter({ $0.contains("Ap") })
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.