下面是有效的代码:
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
循环中使用 as
将 result
向上转换为 aParticipant
时,您可以简单地在 map
中做同样的事情。假设 AParticipant
是一个协议(protocol)(听起来像您收到的错误的情况),您只需要:
let newArray = results.map { $0 as AParticipant }
或者你可以让 Swift 推断向上转换:
let newArray : [AParticipant] = results.map { $0 }
但是,如果 AParticipant
是 results
数组中元素的父类(super class)类型,如 Alexander Momchliov注意,您可以将其简化为:
let newArray = results as [AParticipant]
然而,协议(protocol)类型需要显式的 map
,因为它们具有不同的内存结构,因此每个元素都需要单独转换。查看两者 this Q&A和 this Q&A了解更多信息。
另请注意,我已将 AParticipant
大写,因为类型应为 UpperCamelCase
– 根据 Swift API Design Guidelines .
关于swift - 映射函数重铸数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38776364/