Make App Pie

Training for Developers and Artists

Make Swift Playgrounds Apps : Variables and Scope

Transcript

We’ve been using constants and literal up to now. However, you will want values to change as you build apps. For that, you need variables. Let’s look at variables and how to use them. 

We’ll start with the same code from the last lesson. Try adding to the bottom of the code

size = 10
area = pi * size


You’ll get errors that you cannot assign a value. You need to tell the Swift Compiler you will be changing this value. Fortunately, the difference between a constant and a variable is a keyword. We use var for variables and let for constants. Otherwise, the declarations are identical. 
So If I changed 


var size:Double = 8

And 

var area:CGFloat = pi * size * size 


The error disappears as size and area are now variable and can take multiple values. Run this, and you get the new values. 

Let’s see this a bit more practically. Head over to the app. Make a new file GlobalSettings. Things we put in this file are constants and variables accessible from the entire application. You need to be careful here and only add stuff that you’ll want to control for the whole app. In later lessons, we’ll move this to a settings file. Global variables like this can be dangerous and difficult to debug, so avoid them. However, For very simple stuff like this, they work okay. 

let companyName = "Huli Pizza Company"
let surfgirl = "SurfGirl1"
let pizzaImg = "Pizza"
var color = Color.blue

Now let’s see how these work. Close up the sidebar. Go to contentView. Change the background color by replacing the color with the color variable

.background(color)

And the background turns to blue. 

 I can do the same with the bannerImage

Image(pizzaImg) 

And that changes the image.

Here’s where it gets interesting. Add this to ContentView above the body. 

var bannerImage:String = surfGirl

Now I change the variable in the image to

Image(bannerImage)

And I get the surfer back again. 
What we are seeing is what is known as the scope of the variable. While we’ll discuss it later in more detail, the struct content view contains its variables known as local variables. 

But scope goes one step farther. Add this above bannerImage

var color = Color.green

Our background is green again. Local variables overrode the values of a global variable of the same name. This is why globals are frowned on: it is hard to keep track of what is global and what is local. 

If globals are so hard to track, what do you do when you want to move data into ContenView that isn’t a global? Add the title

var title:String

Text(title)

Which gets us an error. The struct and its counterpart class are how you make custom types. Again we’ll get more into that in a lesson or two, but for now, let’s concentrate on initializers. For the ContentView type to work, all of the variables must be defined. Since title is not defined, it must be passed through a parameter.  

ContentView is called in the MyApp file. Go there and change MyApp. 

ContentView(title: companyName)

Our errors disappear and we see the title. 

MenuItem view is also a type, though we tend to refer to these defined types as objects. I can do the same thing in MenuItemView. 

var imageName:String = pizzaImg

Image(imageName)

Back in ContentView, it didn’t change anything because imageName was specified. But I can change it if I want. 
Add one more MenuItemView, showing the parameter.

MenuItemView(imageName: surfGirl).padding(.leading)

And we get a different image on the third menu item. 

Variables and scope are critical to building apps. Variables let you change values either by assignment or passing them through parameters. However, we are going to want more control over their values. In our next lesson, we’ll use some logic to make decisions and change variables in our code. 

The Whole Code

Playground

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 = 10
area = pi * size

Huli Pizza App

Global settings

import SwiftUI
let companyName = "Huli Pizza Takeout"
let surfgirl = "SurfGirl1"
let pizzaImg = "Pizza"
var color = Color.blue

MenuItemView

import SwiftUI
struct MenuItemView: View {
    var imageName:String = pizzaImg
    var body: some View {
        HStack{
            Image(imageName)
                .resizable()
                .frame(maxWidth:150,maxHeight: 150)
                .clipShape(Circle())
            VStack(alignment:.leading){
                Text("Menu Item")
                Text("Menu Description")
            }
            Spacer()
        }
    }
}

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

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().padding(.leading)
            MenuItemView().padding(.leading)
            MenuItemView(imageName: bannerImage).padding(.leading)
            Spacer()
        }
        .background(color)
    }
}

Leave a comment

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