Filter Array of [AnyObject] in Swift

前端 未结 5 895
借酒劲吻你
借酒劲吻你 2020-12-05 10:25

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

5条回答
  •  醉酒成梦
    2020-12-05 10:45

    Ok, if the array objects contains only Restaurant(s) the following code does work.

    Lets say Restaurant is something like this:

    enum RestaurantType {
        case Sushi, Japanese, Asian
    }
    
    class Restaurant {
        var type = [RestaurantType]()
        // more properties here...
    }
    

    First of all lets define an array of Restaurant(s).

    var restaurants = objects as [Restaurant]
    

    Then we can filter it:

    var sushiRestaurants = restaurants.filter { (restaurant : Restaurant) -> Bool in
        return contains(restaurant.type, .Sushi)
    }
    

    Update: Now I am assuming objects is an array of PFObject(s) Just ignore my previous code and try this:

    var restaurants = objects as [PFObject]
    var sushiRestaurants = restaurants.filter { (restaurant : PFObject) -> Bool in
        return contains(restaurant["Type"], "Sushi")
    }
    

    Maybe it will crash again, the problem is that I don't know the type of Restaurant.Type. I'm trying. Maybe the next error message will provide more useful info.

提交回复
热议问题