小编典典

在Swift中过滤[AnyObject]的数组

swift

AnyObject在Swift中有一组对象。每个对象都有餐厅的属性,例如名称,类型,位置等。如果我想将数组中所有包含类型的对象保留为“
Sushi”,该如何过滤数组。

[AnyObject]具有2个对象的示例数组。过滤器应保留第一个对象(类型: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]):

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!)

阅读 267

收藏
2020-07-07

共1个答案

小编典典

您的数组,objects是一个PFObject对象数组。因此,对于filter数组,您可以执行以下操作:

let filteredArray = objects.filter() {
    if let type = ($0 as PFObject)["Type"] as String {
        return type.rangeOfString("Sushi") != nil
    } else {
        return false
    }
}

基于我们正在处理自定义Restaurant对象的假设,我的原始答案如下:


您可以使用该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是一个字符串数组,您将执行以下操作:

let filteredArray = objects.filter() {contains(($0 as Restaurant).type, "Sushi")}

如果类型数组可以是nil,则可以对其进行条件分解:

let filteredArray = objects.filter() {
    if let type = ($0 as Restaurant).type as [String]! {
        return contains(type, "Sushi")
    } else {
        return false
    }
}

具体情况会有所不同,具体取决于您对的声明Restaurant,您尚未与我们分享此声明,但希望这可以说明这一想法。

2020-07-07