ytbryan
ytbryan

Reputation: 2694

What is the recommended way to break out of a block or stop the enumeration?

So, I just realize that break is only for loop or switch.

enter image description here

Here's my question: Is there a recommended way to break out of a block? For example:

func getContentFrom(group: ALAssetsGroup, withAssetFilter: ALAssetsFilter) {
    group.enumerateAssetsUsingBlock { (result, index , stop) -> Void in

        //I want to get out when I find the value because result contains 800++ elements
    }
}

Right now, I am using return but I am not sure if this is recommended. Is there other ways? Thanks folks.

Upvotes: 11

Views: 9681

Answers (2)

Rashad
Rashad

Reputation: 11197

return is fine, block concept is similar to function, so returning is okay.

Upvotes: 12

Rob
Rob

Reputation: 438202

If you want to stop the current iteration of the enumeration, simply return.

But you say:

I want to get out when I find the value because result contains 800++ elements

So, that means that you want to completely stop the enumeration when you find the one you want. In that case, set the boolean value that the pointer points to. Or, a better name for that third parameter would be stop, e.g.:

func getContentFrom(group: ALAssetsGroup, withAssetFilter: ALAssetsFilter) {
    group.enumerateAssetsUsingBlock() { result, index, stop in

        let found: Bool = ...

        if found {
            //I want to get out when I find the value because result contains 800++ elements

            stop.memory = true
        }
    }
}

Upvotes: 10

Related Questions