• Skip to primary navigation
  • Skip to main content

AmaKit

Amarillo Swift Developer Workgroup

  • Home
  • Our Journal
  • Contact

Swift Programming Fundamentals Cheat Sheet

July 21, 2020 by Kenneth Jackson Leave a Comment

Mobile Application Development Class

  • Basic Teacher: Mark Nair
  • Intermediate Teacher: Dewayne Higgs
  • Advanced Teacher: Dewayne Higgs

A Swift Tour — The Swift Programming Language (Swift 4.2)

Programing Key Elements

  • Write The Code
  • Compile The Code
  • Called “Build” in Xcode
  • Run The Code

Comment

// or /* */

Keywords

The word let is an example of a keyword. Keywords have special meaning in Swift and cannot be used as names.  The let keyword is used to declare a constant. Over time, you’ll be introduced to more Swift keywords.

Constant

The names also known as the identifier for constants start with a lowercase letter and uses a camel case format.

  • let numberOfDogs = 6 + 2
  • let numberOfCats = 5
  • let numberOfTurtles = 2
  • let numberOfHamsters = 1
  • let totalNumberOfAnimals = numberOfDogs + numberOfCats + numberOfTurtles + numberOfHamsters
  • let totalNumberOfMammals = numberOfDogs + numberOfCats + numberOfHamsters

Variable

Variables are the nouns the “things” of programming. They are named containers that hold data. 

  • var  – Variable keyword
  • var score – Variable name
  • var score:Int – Variable data type declared with a colon
  • var score:Int = 100 – Variable value

Rules for Naming Variables

  • Start with a lowercase letter
  • Use letters, numbers, and underscores
  • Use camelCase
  • Don’t use reserved words. (If reserved, the variable name will turn pink, purple, etc)

Method

Methods are the verbs or actions of programming. 

Named sections of codes that are logically grouped.

  1. func  – Function keyword
  2. func  tieShoes() – Function name
  3. { } – Body of method
//define tieShoes method
func tieShoes() {
	// code that runs when tieShoes method is called
}

// execute the tieShoes method

What’s the difference between a function and a method?

func thisIsAFunction() {
}

struct Person {
    func thisIsAMethod() {
    }
}

New Line

\n

Rules for Naming Methods

  • Start with a lowercase letter
  • Use letters, numbers, and underscores
  • Use camelCase
  • Don’t use reserved words. (If reserved, the variable name will turn pink, purple, etc)

Parameters

Conditional Statements – If This Than That Else

  • If/then statements
  • A condition is evaluated as true or false
  • A block of code is executed if the condition is true
  1. if  – Conditional statement keyword
  2. if  tieShoes() 
  3. { }- contains code that runs if the statement is true
  4. else – if conditions is false an else statement can be run following the if statement
if (3 > 2) {
	// code runs if condition is true
}

else {
	// code runs if condition is false
}

Conditional Comparison Operators

OperatorDescriptionExample
>Greater thanif (10 > 1)
<Less thanif (1 < 10)
==Equal toif (“Kenneth” == “Kenneth”)
 ||Or (for two conditions)if (1 == 1 || 1  > 10)
= Sets the value of a variable
== Is equal to

Class – Corresponds to a file

Function

Events

Loops

Functions

https://docs.swift.org/swift-book/LanguageGuide/Functions.html#//apple_ref/doc/uid/TP40014097-CH10-ID158

func spaceAvailablemessage(eachVideoDuration: Int, numberOfVideos: Int) -> String {
    let currentSpace = 10000
    let megabytesPerSecond = 3
    let spaceAvailable = currentSpace - eachVideoDuration * numberOfVideos * megabytesPerSecond
    
    return "If youe \(numberOfVideos) videos are \(eachVideoDuration) seconds each, you will have \(spaceAvailable) MBs remaining"
}

Your functions can have multiple parameters, but can only return one value.

The value that a function returns is just like any other. It can be assigned to a variable or a constant and can be used for other work. at Variables and constant can also be used as the arguments:

let desiredVideoDuration = 40
let holidayVideoCount = 100
let videoMessage = spaceAvailablemessage(eachVideoDuration: desiredVideoDuration, numberOfVideos: holidayVideoCount)
let namedVideoMessage = "Hey Kenneth! \(videoMessage)"

Kinds of Functions

❌ Parameters, ❌ Return value

paintPicture()

✅ Parameters, ❌ Return value

paintPicture(width: Int, height: Int, dominantColor: UIColor)

❌ Parameters, ✅ Return value

paintPicture() -> Painting

✅ Parameters, ✅ return value

paintPicture(width: Int, height: Int, dominantColor: UIColor) -> Painting

Naming Functions

Functions should read like sentences when you call them. You’ll achieve this by carefully choosing names for your parameters and functions.

func makeFavorite(categoryOfThing: String, favorite: String) -> String {
    return "My favorite \(categoryOfThing) is \(favorite)."
}
func makeFavorite(CategoryOfThing: String, favorite: String) -> String {
    return "My favorite \(CategoryOfThing) is \(favorite)."
}
func printHelloTo(_ name: String) {
    print("Hello" + name)
}

Function Inter-dependability

func impossibleBeliefsCount(pigsFlying: Int, frogsBecomingPrinces: Int, multipleLightningStrikes: Int) -> Int {
    let total = pigsFlying + frogsBecomingPrinces + multipleLightningStrikes
    return(total)
}

func impossibleThingsPhrase(numberOfImpossibleThings: Int, meal: String) -> String {
    
    return "Why I've believed as many as \(numberOfImpossibleThings) before \(meal)"
}

let numberOfBeliefs = impossibleBeliefsCount(pigsFlying: 5, frogsBecomingPrinces: 4, multipleLightningStrikes: 4)
let phrase = impossibleThingsPhrase(numberOfImpossibleThings: numberOfBeliefs, meal: "lunch")

print(phrase)

Structures – Structs

https://docs.swift.org/swift-book/LanguageGuide/ClassesAndStructures.html#//apple_ref/doc/uid/TP40014097-CH13-ID82

Basic Operators

https://docs.swift.org/swift-book/LanguageGuide/BasicOperators.html

Assignment Operator

=

Arithmetic Operators

  • Addition (+)
  • Subtraction (-)
  • Multiplication (*)
  • Division (/)

Remainder Operator

%

Logical Operators

  • Logical NOT (!a)
  • Logical AND (a && b)
  • Logical OR (a || b)

Loops

For loop

Iterates a specified number of times. Very useful for processing arrays.

For-each loop

Iterates through each component of a container object such as an array, a list, a tree, etc.

for… in loop

let friends = ["Name", "Name2", "Name3", "Name4", "Name5"]

for friend in friends {
    let sparklyFriend = "✨\(friend)✨"
    print("Hey, \(sparklyFriend), please come to my party on Friday!")
}

print("Done, all friends have been invited.")

While loop – While something is true do this.

do .. while

while .. do

Iterates while a specified condition is TRUE. The condition is tested before the start of each iteration

Do-Until loop

Iterates while a specified condition is TRUE. The condition is tested at the end of each iteration

Simple loop

Sometimes called an infinite loop. Iterates forever unless a conditional statement somewhere within the loop causes execution to break out of the loop.

//let cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

Looping Over a Range

//let cards = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13]

let cards = 1...13

for card in cards {
    if card == 11 {
        print("Jack")
    } else if card == 12 {
        print("Queen")
    } else if card == 13 {
        print("King")
    } else {
        print(card)
    }
}

Generating a Simple Algebraic Expression in Swift

https://stackoverflow.com/questions/43311474/generating-a-simple-algebraic-expression-in-swift

Category iconSwift

Reader Interactions

Leave a Reply Cancel reply

Copyright © AmaKit

Designed by Kenneth Jackson at Connections.Digital in Amarillo, Texas

Powered by WPplaces