Wildcard selector

Learn how to apply a selector across multiple items.

The wildcard selector allows you to access multiple properties or elements at once, which can be useful when you want to retrieve or modify several items in a list, for example.

It iterates over all the items in a list and applies the selector to each item, much like a for loop in programming languages.

Before we explore its use, let's first define a wishlist of must-have items:

1234567
let whishlist = [
["name": "🔮 Crystal ball", "price": 50],
["name": "🎩 Invisible hat", "price": 75],
["name": "👻 Ghost repellent spray", "price": 30],
["name": "🚀 DIY rocket ship kit", "price": 900],
["name": "🦖 Dinosaur egg incubator", "price": 200],
];

Now, let's say you want to calculate the total price of all the items on your wishlist. In this scenario, the wildcard selector comes in handy:

sum of whishlist[*].price

Here the wildcard selector iterates over all the items in the list and creates a new list containing the price of each item. Then, the sum macro calculates and returns the total by summing all the prices in the list.

This also comes in handy when you want to check if a list satisfies a condition. For example, suppose you want to check if at least one item in the user's shopping cart has a price greater than $100. You can use the wildcard selector and the some quantifier to answer this question:

some price in cart.items[*] satisfies price > 100
Try in Playground

This will check if any price in the cart.items list satisfies the given condition. And because the some quantifier returns a boolean, you have your answer.