Make App Pie

Training for Developers and Artists

More if{}else{}

Edited Transcript

Last time we learned the if-else, Let’s expand on that knowledge with more about if-else.
In our code so far, we have several nested comparisons. Each makes only one comparison. What if I wanted to look at two conditions, not one? For example, what if pizzas of sizes 14 to 18 were marked on sale?
We need to find pizzas bigger or equal to 14 and less than or equal to 18.
For these kinds of comparisons, we have three logical operators.
The && operator is AND. For a condition to be true, both sides of the && must be true. This is our case so I could make a line

if size >= 14 && size <= 18{
print("On Sale!")
}

Our 18 pizza is on sale, but a 20 pizza is not.
Now, what if I wanted to make two conditions where if either condition is true, then the expression is true. For example, I’ll make all square pizzas regardless of size on sale over the sized pizzas. I’d use the || operator for OR. Either or both conditions can be true. I could use isRound to determine if this is a round or square pizza, but isRound is false for a square pizza. Our last operator the ! means not, switching true and false. So I can write.

if (size >= 14 && size <= 18) || !isRound {
print("On Sale!")
}

Test again, and our size 20 square pizza is on sale.

You can see if-else statements can get long. Sometimes you quickly want a value. There is another version of the if-else known as the trinary conditional operator, which returns the value of an expression. Suppose in my description, I want to add the shape of the pizza. I could do this:

var shape = isRound ? "Round": "Square"

The ? Acts like the if, then a value for true, a :, and a value for false.
I’ll change the print to include it in the description.

print(sizeName,shape,pizzaName)

Run, and I get the shape in the description.

This is powerful stuff for Swift, but you can also use it in SwiftUI.

Let’s close this up and head over to the Huli pizza takeout MenuItemView

We’ll use this view at times for titles. Those cases do not need descriptions. I’ll add a variable to control this:

var isTitle = false

Then add an if around the menu description.

if !isTitle{
Text("Menu Description")
.font(.caption)
}

To make it look nice, I’ll add the .caption font so that it won’t distract from the menu item. I could also highlight the menu item, but I’ll make it a .title2 font when it is a title with more space. This scenario is a frequent use of the trinary operator.

Text("Menu Item")
.font(isTitle ? .title2 : .headline)

I’ll make a few changes over in ContentView to test this. I’ll add isTitle to the first one.

MenuItemView(isTitle:true).padding(.leading)

And copy the third one, changing the isTitle:

MenuItemView(imageName: bannerImage, isTitle: true).padding(.leading)

And test
And we see this works nicely.
if can be used to select between views. Open the side panel.
Copy the code inside the view for MenuItemview.
Make a new view HMenuItemView

Copy MenuItemView into HMenuItemView

Then do the same for another view, VMenuItemView.

This time, Change the VMenuItemView to reverse the stack views.

Now we’ll change the MenuItemView to select between these two. First, we’ll need another variable.

var isVertical:Bool = false

Change the view to:

if isVertical{
VMenuItemView(imageName: imageName,isTitle: isTitle)
} else {
HMenuItemView(imageName: imageName,isTitle: isTitle)
}

We use the if to select the view to run. Notice what I am doing with the parameters. I’m not doing anything with them in this view. However, I’ll pass along all the parameters to the subviews. This way, they are within the scope of those views.
Finally, I can add the parameter to the first and third entries for MenuItemView, and we’ll see the two types of views appearing. Expand the view with the arrows, and you’ll see better how these all look.
That gives you a good idea of how to use the if in SwiftUI and Swift. We’ve yet to manipulate numbers, and for that, we’ll need something else. In our next lesson, we’ll introduce custom functions and how to make them. So don’t forget to hit subscribe to not miss a lesson.

Code Changed

Starting with this lesson, I’n to going to put all the code as things are getting rather large. I’ll post changes here. If you want the beginning or ending code, I’ve posted it on Gihub here. You download both he beginning and ending state for the code if you want to follow along.

I will post major changes to the code here that I demonstrated up above.

playUI_10


import SwiftUI
var size:Double = 8
let pizzaName:String = "Margherita"
let pi = 3.141
var area:CGFloat = pi * size * size
let isBigPizza:Bool = area >= 1000
size = 25
area = size * size
var isRound = true
if isRound {
    area = pi * area / 4.0
}
print("The area is",area)
var sizeName: String = ""
if size <= 10 {
    sizeName = "Small"
} else{
    if size > 16 {
        sizeName = "Large"
    }
    else {
        sizeName = "Regular"
    }
} 
var shape = isRound ? "Round" : "Square"
print(sizeName,shape,pizzaName)
if size >= 14 && size <= 18 || !isRound {
    print("On Sale!")
}

Huli Pizza Takeout: ContentView

import SwiftUI
//
struct ContentView: View {
    var bannerImage:String = surfgirl
    var color = Color.green
    var title:String
    var body: some View {
        VStack {
            Text(title)
                .font(.largeTitle).bold()
            Image(bannerImage)
                .resizable()
                .scaledToFit()
                .clipShape(RoundedRectangle(cornerRadius: 10))
                .padding()
            Divider()
            MenuItemView(isTitle:true,isVertical: true).padding(.leading)
            MenuItemView().padding(.leading)
            MenuItemView(imageName: bannerImage, isTitle: true,isVertical: true).padding(.leading)
            MenuItemView(imageName: bannerImage).padding(.leading)
            Spacer()
            
        }
        .background(color)
    }
}

Huli Pizza Takeout: MenuItemView

import SwiftUI
struct MenuItemView: View {
    var imageName:String = pizzaImg
    var isTitle = false
    var isVertical = false
    var body: some View {
        if isVertical{
            VMenuItemView(imageName: imageName, isTitle: isTitle)
        } else {
            HMenuItemView(imageName: imageName, isTitle: isTitle)
        }
    }
}

struct MenuItemView_Previews: PreviewProvider {
    static var previews: some View {
        MenuItemView()
    }
}

Huli Pizza Takeout: HMenuItemView

import SwiftUI
struct MenuItemView: View {
    var imageName:String = pizzaImg
    var isTitle = false
    var isVertical = false
    var body: some View {
        if isVertical{
            VMenuItemView(imageName: imageName, isTitle: isTitle)
        } else {
            HMenuItemView(imageName: imageName, isTitle: isTitle)
        }
    }
}

struct MenuItemView_Previews: PreviewProvider {
    static var previews: some View {
        MenuItemView()
    }
}

Huli Pizza Takeout: VMenuItemView

import SwiftUI
//
struct ContentView: View {
    var bannerImage:String = surfgirl
    var color = Color.green
    var title:String
    var body: some View {
        VStack {
            Text(title)
                .font(.largeTitle).bold()
            Image(bannerImage)
                .resizable()
                .scaledToFit()
                .clipShape(RoundedRectangle(cornerRadius: 10))
                .padding()
            Divider()
            MenuItemView(isTitle:true,isVertical: true).padding(.leading)
            MenuItemView().padding(.leading)
            MenuItemView(imageName: bannerImage, isTitle: true,isVertical: true).padding(.leading)
            MenuItemView(imageName: bannerImage).padding(.leading)
            Spacer()
            
        }
        .background(color)
    }
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.

%d bloggers like this: