Swift中的[AnyObject]的过滤器数组

前端之家收集整理的这篇文章主要介绍了Swift中的[AnyObject]的过滤器数组前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有一个Swift的AnyObject对象数组。每个对象都有一个餐厅的属性,如名称,类型,loc等。如果我想保留数组中包含类型为“Sushi”的所有对象,如何过滤数组。

具有2个对象的[AnyObject]样本数组。过滤器应保留第一个对象(类型:寿司):

[<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!)
您的数组,对象是一组PFObject对象。因此,要过滤数组,可以执行以下操作:
let filteredArray = objects.filter() {
    if let type = ($0 as PFObject)["Type"] as String {
        return type.rangeOfString("Sushi") != nil
    } else {
        return false
    }
}

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

您可以使用过滤器方法

我们假设餐厅的定义如下:

class Restaurant {
    var city: String
    var name: String
    var country: String
    var type: [String]!

    init (city: String,name: String,country: String,type: [String]!) {
        ...
    }
}

所以,假设该类型是字符串数组,你可以做一些类似的事情:

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

如果您的类型数组可能为零,则可以对其进行条件展开:

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

具体情况将有所不同,具体取决于您的餐厅声明,您没有与我们分享,但希望这可以说明这一想法。

原文链接:https://www.f2er.com/swift/320444.html

猜你在找的Swift相关文章