Looping through NSMutableArray in Swift

NSMutableArray comes from the Objective-C world. Now you can use generics and strongly-typed arrays, like this:

var vehicles = [Vehicle]()
...
for vehicle in vehicles {
    println(vehicle.registration)
}

This should work:

for vehicle in (vehicles as NSArray as! [Vehicle]) {
    println(vehicle.registration) 
}

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.

Tags:

Ios

Swift