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)
    }
}

Make Swift Playgrounds Apps: Learn About Swift Types

We’ve used integers and strings so far in our code for values. We use each differently, and their use we call a type. Numbers like integers are a type, as are strings as text. Swift is a strongly typed language. To best use Swift, you need to understand the basic types. 

We’re going to use the other swift playground for this. When I want to look at values carefully, the original playground is much better for doing so. So exit out of the app to the browser and tap the button with a plus in a rectangle to load a playground. You won’t be using the sidebar, so you can close that. 

I’ll type in two constants, similar to the ones We’ve used already.  

let size = 18 
let pizzaName = "Margherita"

Press the Run My Code button. You’ll see two new small buttons. Tapping either shows the value of the constant. 

Size is an integer, a number with no fractional value. Integers are very easy for CPUs to work with, so they are the fastest kind of number.  

PizzaName is a string. Strings are made of character combinations represented by sets of numbers. 

You can add strings to strings. You can add Integers to integers. But you can’t add an integer to a string like this

let pizzaName = "Margherita" + size

You get an error because they are different types and don’t mix. 

So far, we’ve used implicit typing to set the types. That means Swift guesses the type by the probable type you assign to the constant. The compiler can get it wrong, so it is a good idea to explicitly set the type with a type declaration. Change the code to this. 

let size:Int = 18
let pizzaName:String = "Margherita"

Int tells the compiler that size is an integer, and string tells the compiler pizzaName is a string. This tells programmers and the swift compiler what you are doing, thus making your code faster and easier to understand. 

There are a lot of different types and variations of types. Int has over a dozen variations alone. However, there are a few types you use more than others. Besides String and Int, you’ll use Double, Float, Bool, and CGFloat most often. 

Double and Float are Floating point numbers, that is, numbers with a decimal point. Float is smaller and less accurate, Double bigger and more accurate. In most code, you’ll want to use Doubles over Floats, but there are cases for an efficient number that use Float. Swift assumes you want a Double. 

Add the following code.  

let pi = 3.141
let area:Double = pi

pi is implicitly typed, and area is explicitly typed to Double. We get no errors because they are. However, change area to  

let area:Double = pi * size * size

And you get an error because the size is an integer. 

Change size to a Float, and it still is an error

let size:Float = 18

You have to make it a DOuble to work. 

let size:Double = 18

There’s another floating-point type which is a little weird, but you’ll see it often called CGFloat. It is the floating-point number used for graphics and layout. Depending on the device, it changes type between Float and Double. However, if you are using Swift playgrounds 4, CGFloat will act like a Double, so it won’t complain about the type change.  

let area:CGFloat = size * size * pi

However, it is not a native swift type, so we still get an error. It is part of a framework called Core graphics, which is included in the swiftUI Framework. If you add at the top of your code 

import SwiftUI

Swift learns what CGFloat is, and the error disappears

The last type you frequently see is Bool. Bool is a true or false type used for testing if something has a similarity or difference from something else. Add this to make a bool to indicate a big pizza.  

let isBigPizza:Bool = area >= 1000

Run the code. You get a true value since the area is more than 1000. Change the value to 8 and it is false. 

Those are the basic types you’ll find in Swift. There are a lot more, and as we’ll see later, you can make your own. In Swift, almost everything is a type. In our next lesson, we’ll move from constants to variables, so be sure to hit the rainbow pizza to subscribe, so you don’t miss any of our exciting lessons.  

The Whole Code

import SwiftUI
let size:Double = 8
let pizzaName:String = "Margherita"
let pi = 3.141
let area:CGFloat = pi * size * size 
let isBigPizza:Bool = area >= 1000

Make Swift Playgrounds Apps: Adding Images

Transcript

We’ve made our basic wireframe, now let’s begin to add  more content. The images we have now wont tell us a much as true images. So we’ll load some images into the icon , the header and the menu items using two placeholders. 

You’ll find like to the photos here and here. Download them and store them in your photos album. 

First we’ll add the surfer to the app icon.  Open the side bar a tap the app settings button. We’ve been using the placeholder, but, tap the custom selection.  Tap Import from Photos. On large images, you’ll get a warning about reducing the size. Click Scale image. Close the settges and the app. You’ll see the icon has changed. 

Go back into the app. Tap the three dots at top to go into multipane mode. Open photos in the second pane.

Find the surfer and drag her over to the sidebar.  Release and she appears in the files list. Do the same with the pizza.  Hold down the name of the surfer, tap Rename and change to surfGirl1

Do the same to the pizza and name it Pizza.

Close the sidebar, 

In contentView, change the image to this: 

Image("SurfGirl1")

You add images by thier name in a string.  We get a huge image of the surfer painting.  To size the image to sometihing reasonable we’ll use two modifiers

.resizable()

Lets the image change size. This must be directly after the image.  Then I’ll add

.scaledToFit()

Which autiomatically scales the image to fit the size of the containg view. 

That looks a lot better. 

Head over to menu item view and replace the circle with  the pizza 

Image("Pizza")

And once you do, if you check the preview. The pizza overwhelms the view. We’ll again use the resizable modifier to control this. 

.resizable()

I get a distored pizza.  There’s another way to size images. we can specify the size of the frame of the image like this

.frame(maxWidth:150,maxHeight:150)

and then we get a square pizza image.  

However we wanted a circle. There is anothere modifier whic changes the shape of the photo called clipshpae. Clipshape takes asa parameter one fo the standard shapes available in SwiftUI: Circles, rounded rectangles, and capsules are threee common ones. So I can add 

.clipShape(Circle())

My image becomes a circle. 

Going back to Content view, we see the pizzas in front of the menu items.  I’ll add a little padding to move them away fro the edge.

.padding(.leading)

I can clip shape the Surfer too. this time I’ll do ti with a rounded rectangle:

.clipShape(RoundedRectangle(cornerRadius:10))

This is starting to look likea real app. Before we get to more in Swift UI We’ll nedd to understand more Swift, in our next lesson we’ll explore more about types and  type declarations. 

Make Swift Playgrounds Apps: Create New Files and Views

Transcript

We have the wireframe for the menu page of our takeout order app, but we have only one menu Item, and we probably want more than that. How can we get more items?  Let’s find out. 

Swift and SwiftUI are a modular language. You build small pieces that do one thing and then and fit them together. 

SwiftUI has Views, but you can make your own from other views. The HStack we have for the menu item can be turned into a view we can use several time to get more menu items. 

Let’s try this. New views need their own files, so first we create the file. 

Open the side tab if It isn’t open yet

 and tap the new file button.  

Select Swift File from the menu that appears. 

In the Code section of the sidebar, New File is highlighted so you can change the name to something else. When Making view we usually end with view. I’ll call this MenuItemView

Tap in the code and the code change to alphabetical order. 

In the code on Line 2 Type View and press return.  All the required code for a view appears.In later lessons We’’l explain what this is all about.  For now you’ll see that MyView is Highlighted in a rectangle. Change that to MenuItemView.

 You’ll also notice the preview now has two dots and some arrows. Tap the arrows ad you’ll see the Hello world from the body.  Delete that. And you get an error. 

Tap Back to ContentView. Highlight all of the HStack Code. 

Cut it. 

Now go to MenuItemView.  Paste it where Hello World was. 

Preview should change to the menu Item code. IF it doesn’t ,try going to ContentView and then back to MenuItemView or leaving the app and returning to it.

You’ve made your own view. Now to use it. 

Go back to Content View and under the divider, Type in 

MenuItemView()

Menu Item show up again. 

Add another MenuItemView Under that one.  And we have two. 

Making views like this is a big part of SwiftUI. You make smaller parts you assemble tog her in a view hierarchy that becomes your app. 

With some of the major parts assembled we can start to add a little content. In the next lesson, we’ll Add some images in place of the circle and rectangle. 

Make Swift Playgrounds Apps: HStack, VStack and Layout

Transcript

We’ve learned some basics of Swift and some fundamental SwiftUI objects. Unfortunately what we’ve done as a demo doesn’t look so nice. So let’s get together the beginnings of a fun app to order pizza!

I’ll start by closing our current app.

Then I’ll make a new app. I’ll  pop out for a second and rename it Huli Pizza Takeout. I’ll make the accent color green this time. 

Inside the app I’ll change the name as we did before to Huli Pizza Takeout

Go to content view, and cut the Text, then paste it on top of the image. 

Change the code to this: 

VStack {
    Text("Huli Pizza Company")
       .font(.largeTitle).bold()
    Image(systemName:"rectangle.fill")
        .imageScale(.large)
        .font(.largeTitle)
}

And we get a different looking app. We have yet to talk about the keyword VStack

VStack is a special object that take code as its parameter. We call these closures. You denote a closure by a code block made of at least  a set of curly brackets. You’ll find code blocks in many places in Swift. The code block of  VStack appears in order Swift UI Views to be displayed vertically. Here we display text then an image, in this case a rectangle. 

Add another View to the stack  

Divider()

Dividers make lines. We’ve seen Spacer before. Spacers has a role of pushing all content in a direction. They fill up all available space. If I put a Spacer at the end of the code block 

Spacer()

It pushes everything to the top. 

We can change the background color of the stack with this modifier added after the code block. 

.background(Color.accentcolor)

There’s another common stack you can use for horizontal arrangement. The HStack arranges views horizontally. As stacks are themselves Views you can have stacks inside their stacks. For example,  below the Divider add this

HStack{
                Image(systemName: "circle.fill")
                Text("menuItem").font(.title)      
            }
            

I have the image and text in stack going from a leading edge to a trailing one. Notice I did not say left to right, because that can change with some languages such as Arabic and Hebrew

Add a Spacer to align to the left. 

Spacer()

You can nest these a deep as you want. I’ll add another VStack to add a description under the Menu Item, so I’ll encompass the Menu Description in the code block. 

VStack(){
    Text("menuItem").font(.title)
    Text("menu Description")
}

This is still centered. I’d have to use more spacer to get it left aligned. Fortunately HStack and VStack have alignment parameters for the alignment at right angles to their direction. For VStack, that means I can align to the leading edge. 

VStack(alignment:.leading){

This is looking good. We’ve built a wireframe for our app. Wire frames are common in app development, where developers use place markers like circles rectangles and a few place marker words to develop the look without worrying about the content.  

There’s usually more than one menu Iten on a menu though, and in our next lesson, we’ll look at a way we can get more Menu Items on to our app. 

The Whole Code

import SwiftUI

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Huli Pizza Company")
                .font(.largeTitle).bold()
            Image(systemName: "rectangle.fill")
                .imageScale(.large)
                .font(.largeTitle)
                .foregroundColor(Color.black)
            Divider()
            HStack{
                Image(systemName: "circle.fill")
                VStack(alignment:.leading){
                    Text("Menu Item")
                    Text("Menu Description")
                }
                Spacer()
            }
            Spacer()
        }
        .background(Color.green)
    }
}

Run Real Apps with Swift Playgrounds for Mac 4.1

A quick review of the changes in Swift Playgrounds 4.1 on the Mac. Learn how you can make and publish an app without Xcode either directly to your Applications folder or to the app store.

Transcript

Apple’s release of Swift Playgrounds 4.1 for macOS might not look like a big change but it is huge. Here’s several thing you can do Straight from playgrounds on a Mac. 

 You can start an app by clicking the button in the lower left. 

You can see your existing  SwiftUI Code on a Mac from files created on iPad. I’ll open the Play4_1 HuliPizza app file and it loads easily, with the Preview working perfectly. 

In 4.1 with macOS 12.4, you can run this directly on the Mac. Drop down menus are functional. 

Stop the app and go to the app setting.  

Capabilities set you up for a variety of device frameworks including files, cameras and internet access, with some specifically for macOS. 

Next you’ll find Team and bundle identifiers if you are a registered App developer.  If you plan to send your app to the app store, set these few settings, and you are ready. You can set you team and bundle here.  Categories and version numbers are set here too. 

Unlike Xcode, If you got all that done, Click the button on the bottom to send your app to app store connect fo posting in the app store. 

Exclusive to macOS version of playgrounds, clicking the button above it installs the playground as an app to your applications folder.  Click on applications and you’ll find it there.

  If you are building in-house Mac apps, there’s nothing easer to get you apps running without Xcode, a developer license or the app store. 

The new format for SwiftUI playground apps is also portable to Xcode.  Just open the file in Xcode and you are ready to go. 

If you are working in swift UI, Or start your app with swiftUI you can a simple lightweight IDE on almost any mac without the heavy overhead of Xcode. Playgounds doesn’t replace Xcove, but if you need to get work done on interfaces , wireframes or prototypes, this is one option you should really consider.  See al this in action in the video above.

Make Swift Playgrounds Apps: Using Functions

Transcript

We have Identifiers for values we can use  repeatedly.  If you think of  constants as nouns we’ll need some verbs to do actions. Swift has actions we can use repeatedly. 

We call these  functions. Here’s a simple example. Add this to your code just below the thing2 declaration.  

let myMax = "\(max(thing,thing2))"

This is a function. A function is a set of code stored somewhere that does something you want done. In this case, the max function finds which number of two numbers is bigger.  

Functions require values to work correctly. You’ll find two ways function obtain values. The max function has in parentheses thing and thing2, We call stuff in the parentheses parameters.  

We’ll make the result on the bottom of our output. Add this to our code. 

Text(myMax)

We’ll see in preview that we get our answer of 11. Text also had parentheses – is Text also a function?

Before I answer that question, let’s look at a string function first, and show you an example of the second and more common way you might use a function in Swift. Change the code to 

Text(myMax.appending(" is bigger"))

If you look at the preview, swift Added  is bigger to 11. In some computer languages, you’d see both myMax and ” is bigger” as parameters, much like max up above. However in object oriented languages, you’ll often find one parameter outside the parentheses , then a dot, and then the function with any parameter it needs. 

When a function takes this form we call it a method. Methods are functions that require a special data type to run. Identifiers assigned to a data type are called objectsmyMax is an object of the String type, and appending is a method of String. Types in swift are usually capitalized. 

So if you go back to Text, is it an object or a type?  Text is a type defined by our user interface framework called SwiftUI. All types have a hidden method called init. The init method sets up a new object of a Type. So our code really reads.

Text.init(myMax.appending(" is bigger")) 

A Text object with the results of  myMax and  ” is bigger “ gets created then used immediately. 

There’s another object called Spacer, which makes variable spacing. If I place it under the code we have I can move everything to the top.  Using Init I’d write it like this. 

Spacer.init()

Because there would be Init everywhere,  in Swift and SwiftUI, we hide init by specifying a type and the parameters of initSpacer had no parameter but you always have to show the parentheses so I get. 

Spacer()

If I hide init.

Apple created a framework called SwiftUI to create user interfaces for your applications in Swift. We’ve been writing in SwiftUI code. Text, Image, VStack, and Spacer are all SwiftUI code. SwftUI has special function it adds to object called modifiers.  You see some modifiers on the Image Object such as imageScale, and foreground color.  There’s also a modifier called bold which works on text.  Add that to our text. 

Text(myMax.appending(" is bigger")).bold()

The text changes to bold. Modifiers change the properties of the object.There is also a font modifier.  I’ll make Hello Pizza use a large title and bold. 

Text("Hello, Pizza!").font(.largeTitle).bold()

And we have a bigger font in bold. 

I’ll change the Image too to use a title font. 

Image(systemName: "\(thing).square")
    .imageScale(.large)
    .foregroundColor(.accentColor)
    .font(.title)

The foregroundColor change the color of text and Sf Symbols. I’ll make it red. Notice this has some predefined values. We can select one of these fro easy color choices. 

Image(systemName: "\(thing).square")
    .imageScale(.large)
    .foregroundColor(.red)
    .font(.title)

            With a few functions, methods and modifiers we’ve changed the look of our app quite a lot. We’ll make some more changes next time as we add some more objects and  Learn to arrange the SwiftUI Objects we have. 

The Whole Code

import SwiftUI

struct ContentView: View {
    let thing = 5 + 3 * 2
    var body: some View {
        let thing2 = thing + 5
        let myMax = "\(max(thing, thing2))"
        VStack {
            Text("Hello, Pizza!").font(.largeTitle).bold()
            Image(systemName: "\(thing).square")
                .imageScale(.large)
                .foregroundColor(.red)
                .font(.title)
            Text("Hello, \(thing2)!")
            Text(myMax.appending(" is bigger")).bold()
            Spacer()
        }
    }
}

Make Playgrounds Apps: Constants and Calculations

Transcript

We’ve got an application started, but it is very hard to change to do anything with.  If I wanted something other than guitars, such as a lightbulb or tv, I’d have to change the entire program. 

Swift playgrounds and its bigger brother on the Mac, Xcode,  have special programs called compilers and interpreters. These take our typed words and make them readable by the chips inside your iPad or Mac. There languages use interpreters too, such as Javascript in your web browser. 

Swift and most programming languages have a way for developers to tell the  that there is a name for a value. We call this a constant. IN swift we assign it  like this above 

let thing = "guitars`

The let is a keyword, a special word that tells Swift that what follows is an assignment of a constant. The word thing is an identifier, a name for a value, which I put after an equals sign.  It can be any word, but we usually leave the first letter lowercase to tell us it is an identifier.

Once you define an indetifier, you can use it. Fro example I can change the Image to this:

Image(systemName: thing)

And we see out guitars

 I can’t put a constant like thing directly into a string, I can however tell the compiler this is a value with interpolation characters of backslash and parentheses like this; 

Text("Hello, \(thing)")

I can change the value of thing, and everything that uses it changes. For example I’ll make it 

let thing = "tv"

And I see tv’s. Or a lightbulb 

let thing = "lightbulb"

And we get lightbulbs.

I’m not limited to strings. I’ll change thing to 5

let thing = 5

And I get an error. If I. Look at the error, it is the compiler whining that Image doesn’t understand integer numbers, only strings.  I can fix that with interpolation, 

`Image(systemName: “\(thing)”)`

And now it works, but is blank. The text shows correctly though. There is no sf symbol named 5 so it is blank. But there is the number 0 through 50   with .square or .circle after it.  So I can change the string to 

Image(systemName: "\(thing).square")

And it works. 

Once you start working with numbers, you can also start working with math. There are four operators you can use  with numbers. The first is addition

let thing = 5 + 3

THIng now equals 8, and we see that in the preview. Subtraction is with a minus sign

let thing = 5 - 3

Which assigns 2, and we see that in the preview too. Division is a forward slash

let thing = 5 / 3

And this gets us a result you might not expect of 1. The numbers we are using are Integers, numbers without fractions, so the result is an integer value.  But there some left over from one and the remainder  operators can show us that

let thing = 5 % 3

Which is two.  IF you really want the fractional value, use a decimal point after the value. 

let thing = 5.0 / 3.0

You’ll see the value but notice we have no symbol. There are only SF symbols for the integer 0 through 50. 

You are not limited to only one operator I’ll change this to 

let thing = 5 * 3 – 1

I get 14. Multiplication and division are calculated before addition and subtraction. 

When a constant is a number you can do math to it, since it represents a number. For example I can do this

Image(systemName: "\(thing + thing ).circle")

I’ve added thing to itself.  I can also make another constant from thing, but you have tone careful. I’ll make a thing2 under thing

let thing2 = thing + 2

And I get an error message.  Cut and paste this Above Vatack, and the error message gets away.  Constant declarations must be in specific places. I’ll discuss why in a later video after we have a few more concepts down. 

Meanwhile we have a new error message which says  thing2 is lonely because no one is using it. I’ll assign it to my text. 

Text("Hello, \(thing2)")

And we get  a response on the preview. 

You’ve covered some more basics of assignment and some of the math functions you can use with integers.  Next time, I’ll show you some more sophisticated  stuff you can do with numbers and strings called functions. 

The Whole Code

if you want to look at everything we’ve done or copy and paste into playgrounds, here’s all the code we’ve used so far.

import SwiftUI

struct ContentView: View {
    let thing = 5 + 3 * 2
    var body: some View {
        let thing2 = thing + 5
        VStack {
            Text("Hello, Pizza!")
            Image(systemName: "\(thing - 1).square")
                .imageScale(.large)
                .foregroundColor(.accentColor)
            Text("Hello, \(thing2)!")
        }
    }
}

Make Playgrounds Apps: First Steps the video

Here’s the video version of the post from last week, Starting this week the video will post with text.

Make Swift Playgrounds 4 Apps: First Steps

Swift Playgrounds 4 changes the game if you want to get into programming on the iOS and iPadOS platforms. Today we start a series that takes you from knowing nothing about programming to writing apps, one step at a time. We’ll use the Swift programming language and the SwiftUI Framework for user interfaces. Along the way we’ll introduce plenty of programming concepts you can transfer to learning other programming languages.

What you’ll Need

All you need is Swift Playgrounds 4. You don’t need any experience programming. However, Swift playgrounds 4 as of this writing has a few requirements of its own. The app only runs on iPads with iOS 15, but I’d suggest 15.4 or later for best results.

You can get the app in the App Store for free.

Swift playgrounds can use the on-screen keyboard, but if you have one, I do suggest using a external keyboard for faster workflow. Usually I’ll be working on a iPad Pro with Magic Keyboard. which will give you more clarity in seeing the code.

As we go through the series, I’ll show you how to use the on-screen keyboard in case you don’t have an external keyboard including some cool tricks for editing. In this first lesson we’ll be using that on-screen keyboard.

First Steps

With Playgrounds installed on your iPad, now. Let’s get your first app running.

Open the playgrounds app. On the bottom you’ll see More Playgrounds.

The first two choices there are App and playground.  We’ll be using the app for our purposes. Tap app. 

At the top of the screen, you’ll get an icon with the name My App. Tap on My App, and you are in the app’s code. At the upper left is a button that says app settings. If you don’t, tap the sidebar button to show it.

Tap that. That sets the appearance of your app in the browser.  Tap name and change it to Hello Pizza. Under placeholder choose, the binoculars, and a blue color accent. 

Tap done and you see in the corner you new icon.

Now to add some code.  Tap the ContentView tab at the top. For many of these lessons we’ll do our work here.  Tap the sidebar button to hide it. 

We’ll discuss all of this code as we go through the series, but for now I want to point you to line 9. Text is a function, a command that tells the iPad to do something. In this case, Text tells the iPad to display the phrase Hello World!. Text will display anything found within those quote marks. Quote marks and the characters it contains are called a string. You can change the string by typing in the quotes. Tap after the d to get a cursor. Change to

Text(“Hello, guitars!”)

You’ll notice the preview on the right change to our new message.

Try typing in another phrase. I’ll put this on the top. Tap after the curly brace for VStack{ press return for a new line and add Tex with the onscreen keyboard. You get two changes:

First, you get the red X with a message. This is a syntax error. It means Swift does not understand what you are trying to say. As you type , you’ll often see this. It should go away after you finish, but if it does not, it means you made a mistake.

The second part is the autocomplete. Playgrounds guesses what you want to type, and give you suggestions. You tap on the correct one and Autocomplete will type for you. On top, autocomplete highlights the best guess Text. There is also on the left a return symbol. Pressing return adds that to your code. press return. Text gets added to your code.

Then add the rest of this

Text(“Hello, Pizza!”)

You’ll find the pizza phrase on top of the globe. 

Now let’s change the globe. We have an Image function here. Some functions have different ways of working, and when they do there will be parameters inside the parentheses. This one has a systemName parameter. systemName wants a string of a system image, what Apple calls an SF Symbol. If you tap the + and the Star at top, you’ll find a list of SF symbols.

Tap outside the list to dismiss it. I want guitars so change the system name to guitars

Image(systemName: "guitars")

The symbol changes to guitars

While it may not be the next video game sensation, you’ve modified the application to be your first program. Basically that’s all there is to programming, putting down statements containing functions like Image and Text to tell a user what to do. Of course there’s a lot of other statements and you will need to store data, make decisions and do the same same thing multiple times. In this series we’ll learn that and a lot more about user interaction.

Stay tuned to more fun next week as we learn about constants, some math, and adding strings together.