1

I have an array of PFObjects. I'd like to search if the "Type" contains "Sushi". The filter alters the array. How can I preform this search without altering the array?

func startCheckOptions(objects: [AnyObject]) {     
  let filteredArray = objects.filter() {
      if let type = ($0 as PFObject)["Type"] as String {
          //if "type" contains "sushi", then do something instead of alter array
          return type.rangeOfString("Sushi") != nil
      } else {
          return false
      }
  }
}

2 Answers 2

3

You can use the contains function:

func startCheckOptions(objects: [AnyObject]) -> Bool {     
    return contains(objects as [PFObject]) { (object) -> Bool in
        if let type = object["Type"] as? String {
            return type.rangeOfString("Sushi") != nil
        }
        else {
            return false
        }
    }
}

if startCheckOptions(objects) {
    println("yes")
}
else {
    println("no")
}

This has the advantage of not building a new array containing the matching objects and stopping on the first match.

In this case you'd be better off protecting the objects cast (or really handling one time somewhere else) by casting it to [PFObject] ASAP. Leaving AnyObject references floating around can only lead to confusion and heartache.

Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the answer. I forgot to mention objects is type [AnyObject] (updated code). The code above generates the error at contains. "Type AnyObject does not conform to protocol Equatable"
thanks this code compiles without error. however, i don't quite understand how I can preform any action if "type" contains "sushi". For instance, I tried printing yes if true and no if false.
Maybe this edit answers your question, if it doesn't, I'm not sure what your question is.
yep, that's actually what I ended up doing, except all within the function (just added a second if statement for hasSushi). I was just wondering if there was a more efficient way because I will be checking multiple "Types"
0

filter() does not alter an array, but it returns a new array. What you have above is correct. objects will be the original array, and filteredArray will be the new array consistent of objects where "type" is "sushi".

2 Comments

Is there a more direct way to check if the original array "Type" contains "Sushi" without requiring a return value.
You can use the contains() function.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.