简体   繁体   English

在Swift中通过NSMutableArray循环

[英]Looping through NSMutableArray in Swift

How can Ioop through an NSMutableArray in Swift? 如何在Swift中通过NSMutableArray? What I have tried: 我尝试过的:

var vehicles = NSMutableArray()

The array contains objects from class: Vehicle 该数组包含来自类: 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 . 如果没有编译器告诉我registration不属于AnyObject我无法运行上面的代码。 At this point I assumed that was because I hadn't told the for loop what type of class item belongs to. 在这一点上,我认为这是因为我没有告诉for循环什么类型的类item属于。 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? 现在编译器抱怨向下转换...如何在循环遍历车辆阵列的同时简单地获得对自定义注册属性的访问权限?

This should work: 这应该工作:

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

As Romain suggested, you can use Swift array. 正如Romain所说,你可以使用Swift数组。 If you continue to use NSMutableArray , you could do either: 如果继续使用NSMutableArray ,您可以执行以下任一操作:

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: 或者,您可以强制打开它,使用where限定符来保护自己免受强制转换:

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. 显然,如果可能的话,问题是你是否可以退出NSMutableArray并使用Array<Vehicle> (又名[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'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. 有时我们会NSMutableArray返回NSMutableArray对象的Objective-C代码,但是如果这个NSMutableArray是在Swift中创建的,那么最好使用Array<Vehicle>

NSMutableArray comes from the Objective-C world. NSMutableArray来自Objective-C世界。 Now you can use generics and strongly-typed arrays, like this: 现在您可以使用泛型和强类型数组,如下所示:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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