mactunes mactunes - 4 months ago 7
Swift Question

Casting array of objects to array of subclassed objects in Swift

I have an array of EKReminder, like so:

var currentReminders: [EKReminder]? = ....


I want to cast this array to an array of subclasses of EKReminder. Let's say this is the subclass:

import Foundation
import EventKit

class NNReminder: EKReminder {
var additionalNotes: String?
}


How would I cast currentReminders to [NNReminder]? I tried several ways but they all failed.

Answer

Provided you are sure that all members of currentReminders are, in fact, NNReminders, you can cast them all like this:

currentReminders = currentReminders.map { $0 as! NNReminder }

Edit: if only some of the reminders are of type NNReminder, or you're not sure of the array's contents, you can use flatMap to remove the nil values:

currentReminders = currentReminders.flatMap { $0 as? NNReminder }

If you are asking how to transform a bunch of objects that were initialized as EKReminder, you should write a custom init in NNReminder that takes an EKReminder, and use this init in the above map method.

Comments