Introduction to Swift

Apr 24 2024 · Swift 5.10, iOS 17, Xcode 15

Lesson 01: Swift Basics

Demo

Episode complete

Play next episode

Next

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Heads up... You’re accessing parts of this content for free, with some sections shown as obfuscated text.

Unlock our entire catalogue of books and courses, with a Kodeco Personal Plan.

Unlock now

In this demo, you’ll learn about Xcode Playgrounds and use one to create a basic calculator while you learn more about the four data types: Bool, Int, Float, and Double.

Building the Calculator

The playground starts with two lines; delete them for now and start building your calculator.

let int1: Int = 10
var int2 = 6
int1 = 6
int2 = 5
// int1 = 6

Boolean Expressions

In a playground, you can write expressions to do things like compare or add two numbers. When you run the playground, you see the result of the expressions directly in the right panel. Add these two expressions:

int1 == int2
int1 > int2
let boolNumbersAreEqual: Bool = int1 == int2
let boolNumbersAreDescending = int1 > int2
let boolNumbersAreEqual: Bool = false
let boolNumbersAreDescending = true

Integer Operations

Like how you created the Bool constants, create four Int constants storing the addition, subtraction, multiplication, and division results of int1 and int2:

let intSum = int1 + int2
let intSubtract = int1 - int2
let intMultiply = int1 * int2
let intDivide = int1 / int2

Float Operations

Now, you’ll do the same calculations but with Float types. Create two new constants of Float type and be sure to mention the type directly to Xcode this time:

let float1: Float = 11.0
let float2: Float = 6.0
let floatSum = float1 + float2
let floatSubtract = float1 - float2
let floatMultiply = float1 * float2
let floatDivide = float1 / float2

Double Operations

Finally, do the same as with Float but with Double constants. Create two constants with direct values and four to save the math operations:

let double1: Double = 11.0
let double2 = 6.0

let doubleSum = double1 + double2
let doubleSubtract = double1 - double2
let doubleMultiply = double1 * double2
let doubleDivide = double1 / double2
See forum comments
Cinema mode Download course materials from Github
Previous: Instruction Next: Strings