简体   繁体   中英

Most efficient way to typecast an array

I am using a framework that asynchronously loads data from the cache of the device and returns it. However, the method, whose definition I can't change, returns an array of AnyObject s. I have class called Attendee of which I am certain the objects belong to. I need to transform the [AnyObject] array into an [Attendee] array. Currently, I am doing this by integrating through the returned array, typecasting each individual object, and storing it elsewhere. I tried to just typecast the array, but I get a swift run-time error with the typecast. Is there a more efficient way to transform the [AnyObject] into [Attendee] than just looping through it?

var attendees: [Attendee] = []
let query = PFQuery(className: "Attendee")
query.findObjectsInBackgroundWithBlock { (objects: [AnyObject]!, error: NSError!) -> Void in
    if( error == nil ) {
        attendees = objects as! [Attendee]
    } else {
        println("Error fetching attendees: \(error) ")
    }
}

Attendee Class Definition

class Attendee: PFObject, PFSubclassing {

    override class func initialize() {
        var onceToken : dispatch_once_t = 0;
        dispatch_once(&onceToken) {
            self.registerSubclass()
        }
    }

    class func parseClassName() -> String! {
        return "Attendee"
    }


}

也许地图会起作用?

let arrayOfAttendee : [Attendee] = arrayOfAnyObjects.map{$0 as! Attendee}

To typecast an array anyObjectArray , use as!. Make sure you have the exclamation mark.

let anyObjectArray: [AnyObject] = ["Hi", "1", "3"]
let castedArray = anyObjectArray as! [String]

Hope this helps!

If you are receiving a run-time error with the typecasting operator as! that could mean that the array doesn't only contain instances of the Attendee class.

The compiler cannot know for certain until runtime that all of the elements in the array can be downcasted to the type you specified so you could receive a run-time error if you use a forced cast.

There are two ways to downcast the array:

Safe one:

if let attendeeArray = anyObjectArray as? [Attendee] {
    // If we are here means that attendeeArray contains only Attendee objects
    for attendee in attendeeArray{

    }
} else{
   // You should warn someone if you were expecting just attendee elements
}

If any element in the Swift array is not actually a Attendee object at runtime, the cast returns nil and the for in block won't be executed.

Unsafe one:

for attendee in anyObjectArray as! [Attendee] {
    // aView is of type UIView
}

This cast is a forced cast, and results in a runtime error if the cast does not succeed.

Finally if there are elements of different types in you array you will need to filter the array.

let attendeeArray = anyObjectArray.filter() {
    return ($0 is Attendee) 
}

Is there a more efficient way to transform the [AnyObject] into [Attendee] than just looping through it

No. Even the direct cast with as! conceals a loop, since it must cast the individual objects. That, in fact, is why you're crashing - the concealed loop reaches an object in the array that it can't cast.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM