swift - 从 swift 3 迁移到 swift 4 - 无法将 String 转换为预期的 String.Element

标签 swift swift3 swift4

我正在将我的代码从 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/

相关文章:

ios - 使用 ARSCNPlaneGeometry 获取 SCNPhysicsShape 会生成球体形状而不是平面

objective-c - Xcode 中的(命名)关键字是什么?

swift - 如何使用 Swift 和 SpriteKit 创建类似吉他的弦乐

swift - 按下时更改 UICollectionView 单元格大小 - Xcode Swift

swift - 如何获取navigationBar.titleTextAttributes?在 Swift 4.0 中工作?

ios - 重新加载 Collection View 后如何解决 UIButton 边框问题

ios - SCNParticleSystem 从文档目录加载

c++ - Swift 中的类

swift - 类型 'UITableViewCell?' 的值没有成员 'delegate'

swift - 在 iOS 10/macOS Sierra Core Data 中调用新的 entity() 方法时出现 EXC_BAD_ACCESS