user1107173 user1107173 - 1 year ago 62
Swift Question

Map function to recast an array

Below is the code that works:

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

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

return newArray

With map I tried:

var newArray ={aParticipant($0)})

I get an error:
aParticipant cannot be constructed because it has no accessible initializers

Is there a way to accomplish this with

Answer Source

As you're using as to upcast result to aParticipant in your for loop, you can simply do the same in a map. Assuming AParticipant is a protocol (sounds like the case from the error you're getting), you just want:

let newArray = { $0 as AParticipant }

Or you can let Swift infer the upcast:

let newArray : [AParticipant] = { $0 }

However, if AParticipant is a superclass type of the elements in your results array, as Alexander Momchliov notes, you can simplify this down to:

let newArray = results as [AParticipant]

An explicit map is required for protocol types however, as they have a different memory structure and therefore each element needs to be converted individually. See both this Q&A and this Q&A for more info.

Also note that I've capitalised AParticipant, as types should be UpperCamelCase – as per the Swift API Design Guidelines.