映射函数以重铸数组

时间:2016-08-04 19:57:26

标签: 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
}

我试过地图:

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

我收到错误:aParticipant cannot be constructed because it has no accessible initializers

有没有办法通过map完成此操作?

2 个答案:

答案 0 :(得分:4)

当您在as循环中使用resultaParticipant转发for时,您可以在map中执行相同操作。假设AParticipant是一个协议(听起来就像你得到的错误一样),你只需要:

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

或者你可以让斯威夫特推断上调:

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

但是,如果AParticipantresults数组中元素的超类类型,如Alexander Momchliov注释,则可以将其简化为:

let newArray = results as [AParticipant]

协议类型需要显式map,因为它们具有不同的内存结构,因此需要单独转换每个元素。有关详细信息,请参阅this Q&Athis Q&A

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

答案 1 :(得分:0)

您实际上可以将该功能折叠成一行:

返回fetchRequestController.fetchedObjects.map {$ 0 as!参与者}