SwiftUI tutorial

Hi guys! I have one question about .filter.
In tutorial Apple show this code:
@State private var showFavoritesOnly = false
Code Block
var filteredLandmarks: [Landmark] {
landmarks.filter { landmark in
(!showFavoritesOnly || landmark.isFavorite)
}
}

var body: some View {
NavigationView {
List(filteredLandmarks) { landmark in
NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
LandmarkRow(landmark: landmark)
}
}
.navigationTitle("Landmarks")
}
}
}

How works this "var filteredLandmarks: [Landmark] { landmarks.filter { landmark in
(!showFavoritesOnly || landmark.isFavorite) }}".
If somebody tell me how it works i will be happy
You can use .filter(_:) to filter through an array providing a closure that should return true or false depending on whether the element should appear in the filtered array.

For the landmarks example, you can think of it as filter through the landmarks array and if we are not showing favourites only or the current element is favourited then this element should be filtered out into the new array.

That might sound a bit confusing so you can also take a look at the documentation for a better summary.
Code Block
landmarks.filter { landmark in
(!showFavoritesOnly || landmark.isFavorite)
}

To make filter work (on the landmarks array), you need to tell it the rule for filtering.

So filter has an argument which is the func to use to filter elements.
In Swift, this func could be written inside the () of filter(), or outside as a closure (a func with no name).

This closure has a syntax: the argument is an element of the array (filter will explore all elements) : to which you give a name, logically landmark. The func (the closure) returns true or false, which will let filter decide to keep or discard element.
The body of a closure is separated from arguments (landmark) by the in keyword.
after in, you have the computation of the return value.

You could write this in longer forms that may help understand:
Code Block
landmarks.filter( { (landmark: Landmark) in return (!showFavoritesOnly || landmark.isFavorite) } )
or
Code Block
landmarks.filter( { landmark in return (!showFavoritesOnly || landmark.isFavorite) } )
or
Code Block
landmarks.filter { landmark in return (!showFavoritesOnly || landmark.isFavorite) }


SwiftUI tutorial
 
 
Q