swift - 映射函数重铸数组

标签 swift

下面是有效的代码:

let aProvider: () -> [aParticipant] = {
    let results = fetchRequestController.fetchedObjects as! [ParticipantFetchResultsProtocol]

    var newArray: Array<aParticipant> = Array()
    for result in results {
        let obj = result as aParticipant
        newArray.append(obj)
    }

    return newArray
}

我试过的 map :

var newArray = results.map({aParticipant($0)})

我得到一个错误:aParticipant cannot be constructed because it has no accessible initializers

有没有办法用 map 来完成这个?

最佳答案

当您在 for 循环中使用 asresult 向上转换为 aParticipant 时,您可以简单地在 map 中做同样的事情。假设 AParticipant 是一个协议(protocol)(听起来像您收到的错误的情况),您只需要:

let newArray = results.map { $0 as AParticipant }

或者你可以让 Swift 推断向上转换:

let newArray : [AParticipant] = results.map { $0 }

但是,如果 AParticipantresults 数组中元素的父类(super class)类型,如 Alexander Momchliov注意,您可以将其简化为:

let newArray = results as [AParticipant]

然而,协议(protocol)类型需要显式的 map,因为它们具有不同的内存结构,因此每个元素都需要单独转换。查看两者 this Q&Athis Q&A了解更多信息。

另请注意,我已将 AParticipant 大写,因为类型应为 UpperCamelCase – 根据 Swift API Design Guidelines .

关于swift - 映射函数重铸数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38776364/

相关文章:

ios - 位置坐标在 swift 中返回 nil

ios - 如何限制 UICollectionView 中的可选单元格

ios - 如何在 SwiftUI 中自定义文本

swift - 如何过滤从核心数据中获取的数据?

快速 coreML : prediction function without "options" parameter

swift - 采用可变数量参数的函数

objective-c - 添加 Bridging-Header.h 后 Swift 编译器优化 -O 不起作用

ios - 用于聊天应用的 Firebase 数据结构

ios - tvO 上的侧键盘

ios - 快速添加动画序列