Swift fundamentals with exercises.
Attention developer: Please read the Swift Language Guide on a topic or watch the YouTube complimentary video before going onto the
Exercises
section below.
1. The Basics
let swiftIntroduced = "2014"
- Type Safety
- Variables
- Constants
- Type Annotation
- Type Inference
- String
- Int
- Float
- Double
- Boolean
- Tuples
- Optionals
- Optional Binding
- nil-coalescing
9 % 4 // 1
- Arithmetic operators:
+, *, -, /
- Remainder or modulo operator
%
- Ternary operator
(condition) ? :
- Unary operator
- Binary operator
- Assignment opeator
- Compound statements
- Comparison operators
>, <, <=, >=, ==, !=
- Closed-range
- Half-open range
- One-sided range
- Logical operators
&&, ||, !a
let char: Character = "🚀"
- String literal
- Multi-line String
- Special characters / escape characters
- Sring initialization syntax
- Value types
- Character
- Concatenaton
- String interpolation
- Unicode
- String.Index
- Substrings
- Prefix and Suffix
let languages = ["C", "Java", "Objective-C", "Swift", "JavaScript"]
- Array
- Iterate
- Dictionary
- Set
- enumerated()
5. Control Flow
print("Please enter a number between 1 and 20 ?")
var input = Int(readLine() ?? "") ?? 2
if !(1...20).contains(input) {
input = 2
}
repeat {
print("Swift is awesome! 😎")
input -= 1
} while input > 0
- switch
- control transfer statements: continue, break, fallthrough
- labeled statements
- for-in loop
- while
- repeat-while
- iterate
- enumerated()
6. Functions
func developerStatus() -> String {
return "Always learning!"
}
- input
- output
- variadic parameters
- in-out parameters
- guard
- return
- parameter
- implicit return
- argument
7. Closures
let add: (Int, Int) -> Int = { $0 + $1 }
add(12, 7) // 19
- trailing closure syntax
- shorthand-syntax
- capturing values
- reference type
- @escaping closure
- implicit return
- multiple trailing closures
8. Enumerations
enum AppError: Error {
case decodingError(Error)
case badURL(String)
case badStatusCode(String)
}
CaseIterable
- Associated Values
- Raw Values
- Implicitly assigned Raw Values
9. Structures
struct Venue {
let address: String
let name: String
let latitude: Double
let longitude: Double
}
- Memberwise Initializer
- Value type
mutating func
- Immutable
10. Classes
class Person {
let name: String
let age: Int
init(name: String, age: Int) {
self.name = name
self.age = age
}
}
class Fellow: Person {
// inherits all properies and methods of the Person parent class
}
- inheritance
- deintializers
- reference type
- pointer
- retain cycle
- identity operator
===
11. Properties
var fullName: String {
return firstName + " " + lastName
}
- stored property
- computed property
lazy
property- setter
- getter
- propety observer
- property wrappers
- Type property
- Instance property
12. Methods
Instance Method
struct Person {
let name: String
func info() {
print("My name is \(name)")
}
}
let person = Person(name: "Alex")
person.info() // instance method
Type Method
struct Person {
let name: String
static func getRaces() -> [String] {
return ["Black", "Asian", "White", "LatinX"]
}
func info() {
print("My name is \(name)")
}
}
Person.getRaces() // type method
- Type method
- Instance method
self
mutating func
@discardableResult
13. Subscripts
struct Person {
subscript(_ address: String) -> String {
return geocode(address)
}
}
let person = Person()
print(person["105 Broadway, New York, NY"]) // 11249
14. Inheritance
class VenueCell: UICollectionViewCell {
// VenueCell inherits all functions and properties from its Parent class, UICollectionViewCell
}
- Overriding
- Subclassing
final
- Base class
- Super class
15. Initialization
class Node {
var value: Int
var next: Node?
init(_ value: Int) {
self.value = value
}
}
- Default initializers
- Memberwise initializers
- Designated initializers
- Convenient initializers
- Failable initializers
- Required initializers
16. Deinitialization
deint
only works within classess
class ItemViewController: UIViewController {
deinit {
// do any cleanup code or remove any notifications or listeners e.g Firebase listener
}
}
struct Person {
var name: String
var phone: Phone?
struct Phone {
var work: String?
var home: String?
}
}
let person = Person(name: "Alice", phone: Person.Phone(work:"917-457-3498", home: nil))
if let workPhone = person.phone?.work {
print("\(person.name)'s work phone number is \(workPhone)'")
// Alice's work phone number is 917-457-3498
} else {
print("\(person.name) does not have a work phone number.")
}
18. Error Handling
enum AppError: Error {
case badYear
case noData
case serverError
}
func currentYear(_ year: Int) throws {
if year == 2020 {
throw AppError.badYear
}
print("Fingers crossed this is a great year for us all.")
}
do {
try currentYear(2020)
} catch {
print(error) // badYear
}
do {
try currentYear(2021) // Fingers crossed this is a great year for us all.
} catch {
print(error)
}
- throw
- throws
- do-catch
try
,try?
andtry!
- Error
Downcasting
class Person {
func info() {
print("This is a person.")
}
}
class Fellow: Person {
override func info() {
print("This person is a fellow.")
}
}
class Singer: Person {
override func info() {
print("This person is a singer.")
}
}
let heather = Fellow()
let bob = Singer()
let people = [bob, heather]
if let person = people[0] as? Singer { // downcast from Person object to a Singer object
person.info() // This person is a singer.
}
Type checking
let objects: [Any] = ["Alex", true, 2021]
if objects[0] is String {
print("\(objects[0]) is a String object.") // Alex is a String object.
}
if objects[1] is Bool {
print("\(objects[1]) is a Bool instance.") // true is a Bool instance.
}
- downcasting
as!
,as?
,as
- type checking
Complete the exercise in Swift Playground or an online IDE like repl.it .
- The Basics, Basic Operators
- Strings and Characters
- Collection Types - Arrays
- Collection Types - Dictionaries
- Collection Types - Sets
- Control Flow
- Optionals
- Functions
- Closures
- Enumerations
- Structs
To evaluate your Swift fundamentals work on any of the following projects as a command line macOS application.
- Black Jack
- Mad Libs Generator
- Rock, Paper, Scissors
- Tic Tac Toe
- Hangman
- Calculator
- Trivia Game
- Text-Based Adventure Game