1

I'm looking for doing a loop on an array but want to stop after a condition. This is what I have now (btw, I'm using Parse as back-end).

let query = PFQuery(className: "MyObject")
query.whereKey("user", equalTo: PFUser.currentUser())
query.findObjectsInBackgroundWithBlock { (objects:[AnyObject]!, error:NSError!) -> Void in
        if error == nil {
            for object in objects {
                print(object.objectId)
            }
        }
}

This code is printing every objectId.

Now let's imagine I want to print every object until my find an object with objectId == "xxx".

How should I do that?

2
  • 1
    you can return or break out of the loop. if objectId == "xxx" { break/return } Commented Oct 28, 2015 at 15:10
  • Does Swift not have the concept of break? That's the standard method of escaping from a loop in most languages. Commented Oct 28, 2015 at 15:12

3 Answers 3

4

If you want to filter objId and perform some code:

let array = ["id1", "id2", "id3", "id4"]
for objId in array where objId != "id3" {
    print(objId)
}
Sign up to request clarification or add additional context in comments.

Comments

3

I think filter is what you're looking for

let objects = [["id": 1], ["id": 2], ["id": 3]]
objects.filter { $0["id"] != 3 }.forEach { print($0) }

Comments

2

try this

 for object in objects {
            print(object.objectId)

      if object.objectId == "xxx"
       {
         // object Name is found
         // if you like to break the execution use "break"
         //break
        }
       else
        {
          // object ID not found
        }
      }

Comments

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.