我正在将我的代码从 swift 3 转换为 swift 4,并在以下代码中遇到此错误。即使我尝试使用 flatmap 来展平数组,我也会得到这个
Cannot convert value of type 'String' to expected argument type 'String.Element' (aka 'Character')
if favoritedProducts.contains("helloWorld") {}
下面的代码行不返回 [String],而是返回 '[String.Element]' 我如何将它转换为 [String]。如果我尝试将其转换为 [String],它会说它总是会失败。
let productIDs = allItems.flatMap{$0.productID}
最佳答案
如果您的 Item
类型具有 非可选 productID
类型的 String
属性,如下所示
struct Item {
let productID: String
}
你有一个 Item
的数组
let allItems: [Item] = ...
然后你可以使用map
方法得到一个productID(s)
数组
let productIDs = allItems.map { $0.productID }
现在 productIDs
是 [String]
。
关于swift - 从 swift 3 迁移到 swift 4 - 无法将 String 转换为预期的 String.Element,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46383874/