altec
altec

Reputation: 155

Can I replace || with && - Apple's SwiftUI tutorial

I'm following Apple's SwiftUI tutorial here and I'm looking at section 2 "Filter the List View" in step 3 line 9 which I've included below.

I was wondering whether || could be replaced with && and have the same effect? (filtering the list of rows by favourites, without any unintended side effects).

In the canvas it has the same effect, though specifically I'm questioning why || was used, as && makes more sense to me.

import SwiftUI

struct LandmarkList: View {
    @State var showFavoritesOnly = false

    var body: some View {
        NavigationView {
            List(landmarkData) { landmark in
                if !self.showFavoritesOnly || landmark.isFavorite {
                    NavigationLink(destination: LandmarkDetail(landmark: landmark)) {
                        LandmarkRow(landmark: landmark)
                    }
                }
            }
            .navigationBarTitle(Text("Landmarks"))
        }
    }
}

struct LandmarkList_Previews: PreviewProvider {
    static var previews: some View {
        LandmarkList()
    }
}

Upvotes: 0

Views: 2951

Answers (2)

RTasche
RTasche

Reputation: 2644

According to De Morgan's Laws

!A && !B == !(A || B)
!A || !B == !(A && B)

So Leo Tabus' approach is right but I think converting the expression adds more complexity to the code. And negating the whole expression having two negations in the expression makes it harder to understand what the result will be. I personally prefer expressions like

if foo == false {}

because it reads more like a sentence compared of

if !foo {}

which is shorter, however.

In the end I find

if self.showFavoritesOnly == false || landmark.isFavorite {}

way more intuitive and easier to understand especially when trying to find a bug after midnight and a 10hrs working day.

Upvotes: 0

Leo Dabus
Leo Dabus

Reputation: 236420

Those operators have different meanings, || means OR while && means AND. So if you use AND instead of OR it won't show any items if you turn ON the filter and only favorites when you turn the filter OFF.

If you really prefer using the AND operator && instead of OR || you would need to check if landmark is not favorite and if the filter is ON are not true.

if !(self.userData.showFavoritesOnly && !landmark.isFavorite) {
    // code
}

Upvotes: 1

Related Questions