The closest equivalent to Python’s any()/all() methods in Swift

Ngo Minh Tri
2 min readJul 12, 2022

The article not only points out the equivalent methods, but also shares how to implement the similar methods in Swift.

any(), all() methods in Python

By exploring Python, I found there are two interesting methods: any(), all().

The any() method returns True if any item in the iteration are true, otherwise it returns False. If the iteration object is empty, the any() method will return False.

The all() function returns True if all items in an iteration are true, otherwise it returns False. If the iteration object is empty, the all() function also returns True.

Before we move forward, I would like to share the object that we are going to use as an example in the next part. Let’s create a protocol: Minionable. The protocol has a color attribute. We create two structs: YellowMinion and PurpleMinion. Both structs conform to the Minionable protocol and inherit its color attribute as default. Let’s set UIColor.yellow for YellowMinion and UIColor.purple for PurpleMinion.

Then, I create two arrays:

Equivalent methods in Swift

With the same idea, we also have two equivalent methods in Swift language:

The contains() returns a Boolean value indicating whether the sequence contains the given element. true if the sequence contains an element that satisfies predicate; otherwise, false.

The allSatisfy() returns a Boolean value indicating whether every element of a sequence satisfies a given predicate. true if the sequence contains only elements that satisfy predicate; otherwise, false.

Predicate: A closure that takes an element of the sequence as its argument and returns a Boolean value that indicates whether the passed element satisfies a condition. — Apple documentation

Advanced idea

Actually, we are able to create the any() and all() methods in Swift.

Let apply to the minions!

any()

all()

Ba-ba-ba-ba-ba-nana 🙌. The outputs are similar.

Hope you enjoy. Thanks for reading! Please give me claps and share if you find interested 👏.

--

--