Quoting via NSMutableArray in Swift

How to execute Ioop through NSMutableArray in Swift? What I tried:

var vehicles = NSMutableArray() 

The array contains objects from the class: Vehicle

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

I cannot run the above code without a compiler telling me that registration does not belong to AnyObject . At this point, I suggested that this is because I did not tell the for loop which class the item class belongs to. So I changed the code:

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

Now the compiler is complaining about downcasting ... how can I just access the user registration property when passing through an array of vehicles?

+8
ios swift
source share
3 answers

This should work:

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

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

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

or, if you only know Vehicle objects, you can force it to expand:

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

or as DNagy suggested:

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

Obviously, if possible, the question arises: can you retire NSMutableArray and use Array<Vehicle> (aka [Vehicle] ). 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 are stuck with Objective-C code that returns NSMutableArray objects, but if this NSMutableArray was created in Swift, it is probably preferable to use Array<Vehicle> .

+11
source share

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

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

All Articles