- Intro to course
- Learning Objectives
- Variables and Constants
- Activity on Variables
- Types
- Break
- Functions
- Activity on Functions
By the end of this lesson, students should be able to:
- Familiarize with Swift Playgrounds
- Identify and create variables & constants
- Identify and define types in Swift
- Formulate and use functions to encapsulate code with parameters and return values
Swift is a programming language to write software for phones, wearables, desktops, servers, and much more.
It was released in June 2014 by Apple. The language is a combination of years of Apple engineering development and the contribution of an open-source community.
Swift is beginner friendly, safe, fast, interactive and optimized for performance and development.
To learn a lot of the course content we will be using Playgrounds. It will be easy and fast to experiment without having to set up an app in Xcode.
Xcode is the environment where we build apps.
- Identify sections
- Calculations
- Comments
- Print statements
- Source editor: where we write code
- Results sidebar: shows results of code
- Execution control: manual or automatic
- Activity viewer: shows status of the playground
- Panel controls: toggle them on or off from the screen
// This is a single line comment
/* This is a comment that can
span over many lines.
Like this.
*/
It's also useful to see what our code is doing. For this we use print statements. The results will print in the debug area or console.
print("Hello, you are ready to write some Swift")
When we handle data in our code, we can give it a name and a type. This makes it easier to reference it later and manipulate it.
let months: Int = 12
The type Int can store integers.
let average: Double = 8.88
The type Double can store decimals with high precision.
The type Float can store decimals with less precision but takes up less memory.
Once we've declared a constant we can't change it's data. So this makes them useful for values that we know they won't change.
If by mistake you try to change the value of a constant, Xcode will throw an error message to let you know.
Cannot assign to value: 'number' is a 'let' constant
Q1: Will the following code snippet run without error? Justify your answer:
let number: Double = 3
What if we need to change the value? For example if we are tracking our bank account balance. Then we use a variable.
var accountBalance: Double = 8000.80
Constants are useful in cases when we know our data can change.
Choose names for your variables and constants that reflect what they are. This will help as documentation and to make your code readable.
Good | Bad |
---|---|
numberOfPets | np |
username | usrnm |
borderColor | temp |
In Swift is common to use camel case.
- Start with lower case
- If the name has more than one word, start the next words with uppercase
- If there is an abbreviation, use the same case for it
Q1: For a video game, which of the following would be best represented with a constant:
- Player name
- Player level
- Player score
- Player location
Q2: Which of the following would be best represented with a variable? Choose all that apply
- Name
- Birthday
- Age
- Home Address
Q3: ____ is used to declare a constant, and ______ is used to declare a variable:
const
,var
const
,let
let
,var
var
,let
Imagine you're creating a simple photo sharing app. You want to keep track of the following metrics for each post:
- Number of likes: the number of likes that a photo has received
- Number of comments: the number of comments other users have left on the photo
- Year created: The year the post was created
- Month created: The month the post was created represented by a number between 1 and 12
- Day created: The day of the month the post was created
For each of the metrics above, declare either a constant or a variable and assign it a value corresponding to a hypothetical post. Be sure to use proper naming conventions.
Source: Swift Fundamentals. Apple Books.In this playground we review the concepts learned so far, experiment using arithmetic operations and also learn about a new type: Strings.
There can be times when we have data of a certain type but need to convert it to another.
var integer: Int = 20
var decimal: Double = 8.5
integer = Int(decimal)
Every time we declare a new variable or constant we add a type annotation. If we do not include it and still assign a value, the Swift compiler can deduce the type. This is called type inference
let height = 155
Sometimes we need a variable to be a certain type even when assigning something different. Let's say we have this:
let height = 155
This would be assigned as an Int by the compiler. Here are several ways to fix it:
let height = Double(8)
let height : Double = 8
let height = 8 as Double
Using type inference, which of the following would be asssigned a Double
type?
var state = "Rhode Island"
let country = "Belgium"
let population = 142000
let speedLimit = 75.0
let char: Character = "a"
let string: String = "a string"
let cheesecakeLover: Bool = true
let coordinates: (Int, Int) = (1, 2) // tuple
From what you know using other programming languages, what's a function? 🤔
They let you enclose a block of code that performs a task. Then when you need to execute that block of code you can call the function to do it.
You can call the function as many times as you need from different places, instead of repeating code all over.
Here's one way to write a function in Swift.
func sayHello() {
print("Hello World, this is me.")
}
We call the function like this:
sayHello() // prints "Hello World, this is me."
Sometimes we need to pass in values to be used inside the function. These are input parameters and go inside the parenthesis, specifying their type, like this:
func printSumOf(value:Int, andValue:Int) {
print("\(value) + \(andValue) = \(value + andValue )")
}
When we call the function, we send the arguments it needs to work.
printSumOf(value:4, andValue:8)
Apple's convention
Try to make your functions read as sentences. This makes it easier to understand what they do. You'll see a lot of Swift documentation written like this.
"Print sum of value 4 and value 8"
We can make it more readable if we use external names.
func printSumOf(value:Int, and value:Int) {
print("\(value) + \(andValue) = \(value + andValue )")
}
printSumOf(value: 4, and: 8)
Now it reads as "Print sum of value 4 and 8"
You can also opt to have no external names and use an underscore.
func printSumOf(_ firstValue:Int, _ secondValue:Int) {
print("\(firstValue) + \(secondValue) = \(firstValue + secondValue )")
}
printSumOf(4,8)
You can also give parameters default values.
func printSumOf(_ firstValue:Int, _ secondValue:Int = 10) {
print("\(firstValue) + \(secondValue) = \(firstValue + secondValue )")
}
Q: Can you figure out how to call the function to use the default value?
So far we've seen functions that print out to console. But in most real life situations we'll need functions that return a value, so we can store it in a variable or use it directly in another operation.
func sumOf(_ firstValue:Int, and secondValue:Int) -> Int {
return firstValue + secondValue
}
let result = sumOf(4, and: 8)
Complete the playground on today's topics if you aren't done yet, submit to Gradescope.