gpt4 book ai didi

swift - 映射函数重铸数组

转载 作者:搜寻专家 更新时间:2023-11-01 06:05:26 24 4
gpt4 key购买 nike

下面是有效的代码:

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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com