Swift 中 [AnyObject] 的过滤器数组 [英] Filter Array of [AnyObject] in Swift
问题描述
我在 Swift 中有一组 AnyObject
对象.每个对象都有一个餐厅的属性,如名称、类型、位置等.如果我想保留数组中包含 type: "Sushi" 的所有对象,我该如何过滤数组.
I have an array of AnyObject
objects in Swift. Each object has attributes of a restaurant, such as name, type, loc, etc. How can I filter the array if I want to keep all objects in the array that contain type: "Sushi".
具有 2 个对象的 [AnyObject]
示例数组.过滤器应该保留第一个对象(类型:sushi):
Sample array of [AnyObject]
with 2 objects. The filter should keep the first object (type: sushi):
[<Restaurant: 0x7ff302c8a4e0, objectId: LA74J92QDA, localId: (null)> {
City = "New York";
Country = "United States";
Name = Sumo Japan;
Type = Sushi, Japanese, Asian;
}, <Restaurant: 0x7ff302daa790, objectId: 0aKFrpKN46, localId: (null)> {
City = "New York";
Country = "United States";
Name = Little Italy;
Type = Italian, Pizza;
}]
当前代码(但我不确定过滤器是否可以搜索 [AnyObject]
的数组):
Current Code (but I'm not sure if the filter can search through an array of [AnyObject]
) :
var query = PFQuery(className:"Restaurant")
query.whereKey("RestaurantLoc", nearGeoPoint:userGeoPoint, withinMiles:50)
query.limit = 2
query.findObjectsInBackgroundWithBlock {
(objects: [AnyObject]!, error: NSError!) -> Void in
if objects != nil {
println("list of objects of nearby")
println(objects)
let searchString = "Sushi"
let predicate = NSPredicate(format: "Type CONTAINS[cd] %@", searchString);
//Line below gives error: '[AnyObject]' does not have a member named 'filteredArrayUsingPredicate'
//let filteredArray = objects.filteredArrayUsingPredicate(predicate!)
推荐答案
您的数组 objects
是 PFObject
对象的数组.因此,要filter
数组,您可能会执行以下操作:
Your array, objects
, is an array of PFObject
objects. Thus, to filter
the array, you might do something like:
let filteredArray = objects.filter() {
if let type = ($0 as PFObject)["Type"] as String {
return type.rangeOfString("Sushi") != nil
} else {
return false
}
}
<小时>
基于我们正在处理自定义 Restaurant
对象的假设,我的原始答案如下:
My original answer, based upon an assumption that we were dealing with custom Restaurant
objects, is below:
您可以使用 filter
方法.
假设 Restaurant
定义如下:
class Restaurant {
var city: String
var name: String
var country: String
var type: [String]!
init (city: String, name: String, country: String, type: [String]!) {
...
}
}
因此,假设 type
是一个字符串数组,您将执行以下操作:
So, assuming that type
is an array of strings, you'd do something like:
let filteredArray = objects.filter() {contains(($0 as Restaurant).type, "Sushi")}
如果您的类型数组可以是 nil
,您可以对其进行有条件的解包:
If your array of types could be nil
, you'd do a conditional unwrapping of it:
let filteredArray = objects.filter() {
if let type = ($0 as Restaurant).type as [String]! {
return contains(type, "Sushi")
} else {
return false
}
}
根据您未与我们分享的 Restaurant
声明,细节会有所不同,但希望这说明了这个想法.
The particulars will vary a little depending upon your declaration of Restaurant
, which you haven't shared with us, but hopefully this illustrates the idea.
这篇关于Swift 中 [AnyObject] 的过滤器数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!