CACS351 Mobile Programming

Mobile ProgrammingUnit 108 min read

iOS Programming Basics: Swift, ViewControllers, and Core Concepts

Unit 10 of Mobile Programming introduces Swift as the primary language for iOS app development, covering ViewControllers, basic syntax, and how to structure iOS apps using Storyboards and code. It also explores Swift’s unique features like optionals, closures, and memory management, with hands-on examples like factoria

1. Introduction to iOS Programming and Swift

iOS apps are built using Swift, Apple’s modern, fast, and expressive programming language. Unlike Android’s Java/Kotlin, Swift is designed specifically for Apple’s ecosystem (iPhone, iPad, Mac, Apple Watch). Below are key differences between Swift and Android’s Java/Kotlin:

mindmap:
  root((iOS vs Android))
    Swift((Swift))
      - Syntax: Concise, expressive
      - Memory: Automatic Reference Counting (ARC)
      - Platform: Apple ecosystem only
      - Performance: Optimized for Apple hardware
    Java/Kotlin((Java/Kotlin))
      - Syntax: Verbose, object-oriented
      - Memory: Manual garbage collection (GC)
      - Platform: Cross-platform (Android, web, etc.)
      - Performance: JIT compilation
      - "Note: ARC vs GC comparison added for clarity"

Why Swift?

  • Fast development: Playgrounds allow instant feedback.
  • Safety: Strong type checking and optionals prevent crashes.
  • Performance: Near-native speed due to LLVM compiler.

First Swift Program: Factorial Calculation

A common exam question is writing a Swift function to calculate factorial. Below is the code and a traced run:

func factorial(n: Int) -> Int {
    if n == 0 || n == 1 {
        return 1
    }
    return n * factorial(n - 1)
}

let result = factorial(n: 5)
print("Factorial of 5 is \(result)") // Output: 120

Trace Table:

Step Function Call Return Value
1 factorial(5) 5 * factorial(4)
2 factorial(4) 4 * factorial(3)
3 factorial(3) 3 * factorial(2)
4 factorial(2) 2 * factorial(1)
5 factorial(1) 1

2. ViewController: The Core of iOS Apps

A ViewController manages a screen (view) and its user interactions. It inherits from UIViewController and contains:

  • A view hierarchy (UI elements like buttons, labels).
  • Logic to handle user actions (e.g., button taps).

Example: ViewController Structure

ViewControllerUI ElementsSwift LogicLifecycle
Hierarchical breakdown of a ViewController’s components

Swift Code for a ViewController

import UIKit

class MyViewController: UIViewController {
    @IBOutlet weak var label: UILabel!

    override func viewDidLoad() {
        super.viewDidLoad()
        label.text = "Hello, iOS!"
    }
}

Key Methods:

  • viewDidLoad(): Called once when the view loads.
  • @IBOutlet: Connects UI elements (e.g., label) to code.

3. Storyboards vs. Code-Based UI

Storyboards visually design UI layouts, while code-based UI (e.g., UIView) builds interfaces programmatically.

Storyboard Example

  1. Drag a Label and Button onto a storyboard.
  2. Connect the button’s IBAction to a Swift function.
sequenceDiagram
    participant U as User
    participant VC as ViewController
    participant SB as Storyboard

    U->>VC: Taps Button
    VC->>SB: Loads UI from storyboard
    VC->>VC: Calls `buttonTapped()`

Code-Based UI Example

let button = UIButton(frame: CGRect(x: 100, y: 100, width: 100, height: 50))
button.setTitle("Tap Me", for: .normal)
button.addTarget(self, action: #selector(buttonTapped), for: .touchUpInside)
view.addSubview(button)

4. Swift Syntax Highlights

Optionals: Handling Uncertainty

Swift uses optionals (?) to avoid crashes when data might be missing.

var optionalNumber: Int? = nil
let safeNumber = optionalNumber ?? 0 // Defaults to 0 if nil
print(safeNumber) // Output: 0

Closures: Lightweight Functions

Closures are anonymous functions used for callbacks (e.g., button taps).

let greet = { (name: String) -> String in
    return "Hello, \(name)!"
}
print(greet("Alice")) // Output: Hello, Alice!

5. Memory Management in Swift

Swift uses Automatic Reference Counting (ARC) to manage memory:

  • Retain cycles are avoided with weak/unsafe references.
  • Objects are deallocated when no longer needed.
Retain CycleWeak (No Retain)Unowned (No Retain)DeallocatedObject AObject BWeak ReferenceUnowned Reference
ARC: Retain cycles and weak/unowned references

6. Real-World Applications of Swift

In the Real World

  1. WhatsApp (Apple Version):

    • Uses Swift for iOS features like SwiftUI (declarative UI framework).
    • Example: SwiftUI’s @State property wrapper tracks UI changes efficiently.
  2. Khalti (Nepal’s Payment Gateway):

    • Swift powers the iOS app’s secure payment flows (e.g., handling optionals for failed transactions).
  3. Pathao (Ride-Hailing App):

    • Swift’s closures simplify event handling (e.g., real-time location updates).

Worked Example: Daraz Order Queue

Imagine a Swift function to simulate a queue of orders (like Daraz’s delivery system):

Order1Order2Order3Order4FRONTREARoutin
Queue data structure for Daraz order processing (FIFO)
struct Order {
    let id: Int
    let status: String
}

class OrderQueue {
    private var orders: [Order] = []

    func enqueue(order: Order) {
        orders.append(order)
    }

    func dequeue() -> Order? {
        return orders.isEmpty ? nil : orders.removeFirst()
    }
}

// Trace:
let queue = OrderQueue()
queue.enqueue(order: Order(id: 1, status: "Processing"))
queue.enqueue(order: Order(id: 2, status: "Shipped"))
print(queue.dequeue()!.status) // Output: "Processing"

7. Exam Tip

  • Focus on:
    • Defining ViewController and its lifecycle methods.
    • Writing Swift functions (e.g., factorial, array operations).
    • Comparing Storyboards vs. code-based UI.
    • Understanding optionals and closures (common in exams).
  • Avoid:
    • Overcomplicating syntax (stick to basics like loops, conditionals).
    • Forgetting to handle optionals (e.g., ?? operator).
  • Practice:
    • Implement a simple ViewController with a button and label.
    • Write a Swift function to solve a problem (e.g., sum of array).
010122034305
Optional binding example: Handling nil values in arrays

8. Common Exam Questions and Answers

Q1: Define ViewController. Write a Swift program to calculate factorial.

Answer: A ViewController manages a screen’s UI and logic in iOS apps. Below is the factorial program:

func factorial(n: Int) -> Int {
    guard n >= 0 else { return -1 } // Handle invalid input
    return n == 0 ? 1 : n * factorial(n - 1)
}
print(factorial(n: 4)) // Output: 24

Q2: Write a Swift program to find the sum of a 1-D array.

Answer:

let numbers = [1, 2, 3, 4, 5]
let sum = numbers.reduce(0, +)
print("Sum: \(sum)") // Output: 15

9. Comparison Table: Swift vs. Android (Java/Kotlin)

Feature Swift Java/Kotlin
Language Type Multi-paradigm (OOP, FP) OOP
Memory Management ARC (Automatic) Garbage Collection
Syntax Concise, expressive Verbose
Platform Apple-only Cross-platform
Performance Near-native speed JIT-compiled

10. Visual Summary: Swift’s Key Concepts

Swift BasicsViewControllerOptionalsClosuresARC
Swift’s key concepts with hierarchical relationships

Based on the TU BCA syllabus for Mobile Programming (CACS351), unit 10.

Discussion

Loading…