prasadsachidananda / Swift-Fundamentals

Swift fundamentals with exercises.

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

Swift Fundamentals

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.

Table of Contents

let swiftIntroduced = "2014"

Glossary

  • Type Safety
  • Variables
  • Constants
  • Type Annotation
  • Type Inference
  • String
  • Int
  • Float
  • Double
  • Boolean
  • Tuples
  • Optionals
  • Optional Binding
  • nil-coalescing

Video: Swift, The Basics

9 % 4 // 1 

Glossary

  • 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

Video - Swift Basic Operators

let char: Character = "πŸš€"

Glossary

  • 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
  1. Video - Strings and Characters
  2. Strings and Characters code examples
let languages = ["C", "Java", "Objective-C", "Swift", "JavaScript"]

Glossary

  • Array
  • Iterate
  • Dictionary
  • Set
  • enumerated()

Arrays

  1. Video - Arrays
  2. Arrays code examples

Sets

  1. Video - Sets
  2. Sets code examples

Dictionaries

  1. Video - Dictionaries
  2. Dictionaries code examples
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

Glossary

  • switch
  • control transfer statements: continue, break, fallthrough
  • labeled statements
  • for-in loop
  • while
  • repeat-while
  • iterate
  • enumerated()
  1. Video: Control Flow
  2. Control Flow code examples
func developerStatus() -> String {
  return "Always learning!"
}

Glossary

  • input
  • output
  • variadic parameters
  • in-out parameters
  • guard
  • return
  • parameter
  • implicit return
  • argument
  1. Video: Functions
  2. Functions code examples
let add: (Int, Int) -> Int = { $0 + $1 }
add(12, 7) // 19

Glossary

  • trailing closure syntax
  • shorthand-syntax
  • capturing values
  • reference type
  • @escaping closure
  • implicit return
  • multiple trailing closures
  1. Video: Closures
  2. Closures code examples
enum AppError: Error {
  case decodingError(Error) 
  case badURL(String)
  case badStatusCode(String)
}

Glossary

  • CaseIterable
  • Associated Values
  • Raw Values
  • Implicitly assigned Raw Values
Introduction to enums
  1. Video: Enumerations
  2. Enums code examples
Methods and Properties in enums
  1. Video: Enums - Methods and Properties
  2. Code examples
struct Venue {
  let address: String 
  let name: String 
  let latitude: Double
  let longitude: Double
}

Glossary

  • Memberwise Initializer
  • Value type
  • mutating func
  • Immutable
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    
}

Glossary

  • inheritance
  • deintializers
  • reference type
  • pointer
  • retain cycle
  • identity operator ===
var fullName: String {
  return firstName + " " + lastName
}

Glossary

  • stored property
  • computed property
  • lazy property
  • setter
  • getter
  • propety observer
  • property wrappers
  • Type property
  • Instance property

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

Glossary

  • Type method
  • Instance method
  • self
  • mutating func
  • @discardableResult
struct Person {
  subscript(_ address: String) -> String {
    return geocode(address)
  }
}

let person = Person() 
print(person["105 Broadway, New York, NY"]) // 11249
class VenueCell: UICollectionViewCell {
  // VenueCell inherits all functions and properties from its Parent class, UICollectionViewCell
}

Glossary

  • Overriding
  • Subclassing
  • final
  • Base class
  • Super class
class Node {
  var value: Int 
  var next: Node? 
  init(_ value: Int) {
    self.value = value
  }
}

Glossary

  • Default initializers
  • Memberwise initializers
  • Designated initializers
  • Convenient initializers
  • Failable initializers
  • Required initializers

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.")
}
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)
}
Glossary
  • throw
  • throws
  • do-catch
  • try, try? and try!
  • Error

19. Type Casting

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

Glossary

  • downcasting
  • as!, as?, as
  • type checking

Exercises

Complete the exercise in Swift Playground or an online IDE like repl.it .

  1. The Basics, Basic Operators
  2. Strings and Characters
  3. Collection Types - Arrays
  4. Collection Types - Dictionaries
  5. Collection Types - Sets
  6. Control Flow
  7. Optionals
  8. Functions
  9. Closures
  10. Enumerations
  11. Structs

Projects

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

About

Swift fundamentals with exercises.

License:MIT License