- Java 双重比较
- java - 比较器与 Apache BeanComparator
- Objective-C 完成 block 导致额外的方法调用?
- database - RESTful URI 是否应该公开数据库主键?
下面是有效的代码:
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/
我正在尝试创建一个简单的国际象棋程序,但在实现典当推广时遇到了一些小问题。我有一个抽象类 Piece 和扩展它的 6 个类(King、Queen、Rook、Knight、Bishop 和 Pawn)。
这个问题在这里已经有了答案: Convert data from long format to wide format with multiple measure columns (5 个回答) 3年
我正在使用具有 A* 寻路算法的库 (libtcod)。我的类继承了回调基类,我实现了需要的回调函数。这是我的通用示例: class MyClass : public ITCODPathCallbac
在配置重铸机器人时,有没有办法设置一个操作来重置除特定字段之外的所有内存? 我已经尝试取消设置除我需要的字段之外的所有字段,但它很无聊、不可扩展、不可扩展且不可维护。 谢谢 最佳答案 您应该在 Rec
我希望我的 recast.bot 回复用户的回复。这是代码,但我收到以下错误消息。如何解决这个问题? Bot Server is running on port 5002 TypeError: Can
我是一名优秀的程序员,十分优秀!