Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Looping through NSMutableArray in Swift

Tags:

ios

swift

How can Ioop through an NSMutableArray in Swift? What I have tried:

var vehicles = NSMutableArray()

The array contains objects from class: Vehicle

for vehicle in vehicles {
    println(vehicle.registration)
}

I cannot run the above code without the compiler telling me registration doesn't belong to AnyObject. At this point I assumed that was because I hadn't told the for loop what type of class item belongs to. So I modified by code:

for vehicle: Vehicle in vehicles {
    println(vehicle.registration)
}

Now the compiler complains about downcasting... how can I simply gain access to the custom registration property whilst looping through the array of Vehicles?

like image 644
jskidd3 Avatar asked Feb 08 '15 13:02

jskidd3


2 Answers

This should work:

for vehicle in (vehicles as NSArray as! [Vehicle]) {
    println(vehicle.registration) 
}
like image 121
dnnagy Avatar answered Oct 06 '22 03:10

dnnagy


As Romain suggested, you can use Swift array. If you continue to use NSMutableArray, you could do either:

for object in vehicles {
    if let vehicle = object as? Vehicle {
        print(vehicle.registration)
    }
}

or, you can force unwrap it, using a where qualifier to protect yourself against cast failures:

for vehicle in vehicles where vehicle is Vehicle {
    print((vehicle as! Vehicle).registration)
}

or, you can use functional patterns:

vehicles.compactMap { $0 as? Vehicle }
    .forEach { vehicle in
        print(vehicle.registration)
}

Obviously, if possible, the question is whether you can retire NSMutableArray and use Array<Vehicle> (aka [Vehicle]) instead. So, instead of:

let vehicles = NSMutableArray()

You can do:

var vehicles: [Vehicle] = []

Then, you can do things like:

for vehicle in vehicles {
    print(vehicle.registration)
}

Sometimes we're stuck with Objective-C code that's returning NSMutableArray objects, but if this NSMutableArray was created in Swift, it's probably preferable to use Array<Vehicle> instead.

like image 45
Rob Avatar answered Oct 06 '22 01:10

Rob