Unit 1: Introduction to iPhone and iOS Platform with Swift

INT372 — Iphone Application Programming 9 min read

I. Platform Orientation

iPhone application programming is the development of software for Apple’s iOS platform, introduced with the original iPhone (2007). Modern applications are commonly written in Swift, Apple’s type-safe programming language introduced in 2014, and built using tools such as Xcode, the iOS SDK, SwiftUI, and UIKit.

A. Defining Characteristics

The iOS development environment combines a programming language, operating-system frameworks, development tools, and a controlled application lifecycle.

  • Swift language: Provides modern features such as type inference, optionals, closures, generics, structures, enumerations, and automatic memory management.
  • Xcode: Apple’s integrated development environment for writing code, designing interfaces, testing, debugging, and distributing applications.
  • iOS SDK: Supplies frameworks such as UIKit, SwiftUI, Foundation, Core Data, and Core Location.
  • Application lifecycle: Controls states such as launching, active use, background execution, suspension, and termination.
  • Platform conventions: Applications operate in a sandbox, follow Apple interface guidelines, and normally reach users through the App Store.
  • Compilation model: Swift source code is compiled into native machine code, supporting high performance on Apple hardware.

II. iOS and macOS — Apple’s Mobile and Desktop Platforms

iOS and macOS share Apple technologies, including Swift, Xcode, Foundation, and Darwin-based operating-system components, but they target different devices and interaction models.

A. Difference between iOS and MAC OS

The principal difference is that iOS is designed for mobile, touch-oriented devices, whereas macOS is designed for desktop and notebook computers.

  1. iOS

    • Target devices: Runs primarily on iPhone; iPad now uses the related iPadOS platform.
    • Interaction: Uses touch gestures, an on-screen keyboard, sensors, cameras, and device orientation.
    • Interface frameworks: Commonly uses UIKit or SwiftUI.
    • Resource model: Applies stricter limits to background execution, storage access, and inter-application communication.
    • Distribution: Applications are generally signed and distributed through the App Store or approved organizational channels.
    • File access: Each application normally works inside its own sandboxed container.
  2. macOS

    • Target devices: Runs on Mac desktop and notebook computers.
    • Interaction: Emphasizes keyboard, mouse, trackpad, windows, menus, and multiple displays.
    • Interface frameworks: Commonly uses AppKit or SwiftUI.
    • Resource model: Permits broader multitasking, window management, and file-system access with appropriate permissions.
    • Distribution: Software may be distributed through the Mac App Store or directly by identified developers.
    • Shared foundation: Both platforms support Swift and frameworks such as Foundation, but platform-specific APIs are not automatically interchangeable.

III. Object-Oriented Design — Modelling with Objects

Object-oriented programming models software as interacting objects that combine data with operations. In Swift, classes support core object-oriented ideas, while structs and enums also provide powerful modelling capabilities.

A. Object-oriented programming

Object-oriented programming organizes an application around types, instances, properties, and methods.

  • Class: A blueprint defining stored data and behaviour; for example, Vehicle may define speed and accelerate().
  • Object: A runtime instance of a class, such as let car = Vehicle().
  • Encapsulation: Keeps related data and behaviour together and restricts access through modifiers such as private.
  • Inheritance: Allows a subclass to reuse or override superclass behaviour.
  • Polymorphism: Permits code to work with a common superclass or protocol while instances provide different implementations.
  • Abstraction: Exposes essential operations while hiding implementation details; a protocol can require behaviour without specifying its code.
  • Swift emphasis: Swift supports object-oriented programming but frequently favours protocol-oriented design and value types over deep inheritance hierarchies.

IV. Classes — Reference-Type Blueprints

A Swift class defines a reference type whose instances share identity. Assigning a class instance to another variable copies a reference rather than creating an independent object.

A. Declaring and defining classes

A class is declared with the class keyword and defined by its properties, initializers, methods, and optional inheritance relationship.

SWIFT
class BankAccount {
    private(set) var balance: Double

    init(openingBalance: Double) {
        balance = openingBalance
    }

    func deposit(_ amount: Double) {
        guard amount > 0 else { return }
        balance += amount
    }
}

let account = BankAccount(openingBalance: 500)
account.deposit(200)
  • Declaration: class BankAccount introduces the new reference type.
  • Stored property: balance stores a Double; private(set) allows public reading but restricts modification.
  • Initializer: init(openingBalance:) establishes a valid initial state.
  • Instance method: deposit(_:) operates on a particular account.
  • Instantiation: BankAccount(openingBalance: 500) creates an object.
  • Identity: The operator === checks whether two class references point to the same instance.
  • Inheritance syntax: class SavingsAccount: BankAccount declares BankAccount as the superclass; Swift classes support single class inheritance.

V. Data Storage — Named and Indexed Values

Swift stores program data in constants and variables, while arrays organize ordered collections of values of a common type.

A. Variables

Variables are named storage locations declared with var; constants are immutable bindings declared with let.

SWIFT
var score: Int = 10
score = 15

let applicationName = "Weather"
  • Mutability: score may change because it uses var; applicationName cannot be reassigned because it uses let.
  • Type annotation: : Int explicitly states the type.
  • Type inference: Swift infers applicationName as String from its initial value.
  • Type safety: Assigning "high" to score is invalid because a String is not an Int.
  • Scope: A local variable exists within its enclosing function or block; a property belongs to an instance or type.
  • Optionals: var nickname: String? can contain a string or nil, representing the absence of a value.

B. Arrays

An array is an ordered, zero-indexed collection whose elements normally have the same type.

SWIFT
var cities: [String] = ["Delhi", "Chennai"]
cities.append("Mumbai")
let firstCity = cities[0]
  • Type: [String] is shorthand for Array<String>.
  • Ordering: Elements retain their sequence; index 0 refers to "Delhi".
  • Mutation: A variable array supports append, insert, remove, and element replacement.
  • Bounds: Accessing an index outside 0..<cities.count causes a runtime error.
  • Iteration: for city in cities processes each element without manual index management.
  • Safe access: Properties such as first return an optional because the array may be empty.

VI. Behaviour and Communication — Executable Operations

Swift types define behaviour through methods, while communication occurs through method calls and, in Objective-C terminology, message sending.

A. Methods and messages

A method is a function associated with a type; a message is a request for an object to execute a method.

SWIFT
class Lamp {
    var isOn = false

    func switchOn() {
        isOn = true
    }
}

let lamp = Lamp()
lamp.switchOn()
  • Instance method: switchOn() operates on the instance referenced by lamp.
  • Call syntax: lamp.switchOn() invokes the method using dot notation.
  • Parameters: func move(to position: Int) receives a labelled argument through move(to: 5).
  • Return value: func status() -> Bool declares that the method returns a Boolean.
  • Type method: A method marked static belongs to the type rather than an instance.
  • Terminology: Objective-C describes [lamp switchOn] as sending a message. Swift generally uses direct method-call terminology, although Objective-C runtime messaging remains relevant when interoperating with Cocoa APIs.

VII. Closures — Self-Contained Blocks of Behaviour

A closure packages executable code that can be stored, passed to functions, and executed later. Swift functions are named closures, while closure expressions provide compact unnamed forms.

A. Closure

Closures capture constants and variables from their surrounding context and are widely used for callbacks and collection processing.

SWIFT
let numbers = [3, 1, 2]
let sortedNumbers = numbers.sorted { first, second in
    first < second
}
  • Closure expression: { first, second in first < second } supplies comparison behaviour to sorted.
  • Parameters: first and second are inferred as Int.
  • Return value: The Boolean expression indicates whether first should precede second.
  • Type form: (Int, Int) -> Bool means two Int parameters produce a Bool.
  • Shorthand arguments: The same closure may be written as numbers.sorted { $0 < $1 }.
  • Capture: A closure can retain surrounding values; escaping closures may therefore affect object lifetimes.
  • Escaping closure: @escaping is required when a passed closure is stored or executed after its function returns.

VIII. Dictionaries — Keyed Collections

A dictionary stores unordered key-value associations and provides efficient lookup through unique, hashable keys.

A. Dictionary

Each dictionary value is retrieved by its key rather than by a numeric position.

SWIFT
var marks: [String: Int] = [
    "Asha": 90,
    "Ravi": 84
]

marks["Ravi"] = 88
let ashaMark = marks["Asha"]
  • Type: [String: Int] maps String keys to Int values.
  • Unique keys: "Asha" can identify only one current value.
  • Optional lookup: marks["Asha"] returns Int? because the key might not exist.
  • Insertion and update: Assigning through a subscript adds a new key or replaces its existing value.
  • Removal: marks["Ravi"] = nil removes the entry.
  • Iteration: for (name, mark) in marks accesses each key-value pair; iteration order should not be treated as a sorting guarantee.

IX. Structures — Value-Type Models

A structure groups related properties and methods into a value type. Structs are widely used in Swift because copying them creates independent values.

A. Struct

Structures suit models that represent data without requiring shared object identity or class inheritance.

SWIFT
struct Point {
    var x: Double
    var y: Double

    mutating func moveRight(by distance: Double) {
        x += distance
    }
}

var point = Point(x: 2, y: 4)
point.moveRight(by: 3)
  • Value semantics: Assigning point to another variable creates a separate copy.
  • Memberwise initializer: Swift automatically provides Point(x:y:) when appropriate.
  • Mutation rule: A method changing structure properties must use mutating.
  • Inheritance: Structs cannot inherit from other structs or classes, though they can conform to protocols.
  • Typical uses: Coordinates, configuration values, SwiftUI views, and small domain models commonly use structs.
  • Design choice: Prefer a struct unless shared identity, inheritance, or reference semantics are specifically required.

X. Enumerations — Finite Sets of Cases

An enumeration defines a type with a restricted set of valid cases, making program states explicit and type-safe.

A. Enum

Swift enums can include raw values, associated values, methods, and protocol conformances.

SWIFT
enum NetworkState {
    case idle
    case loading
    case success(String)
    case failure(Int)
}

let state = NetworkState.success("Loaded")
  • Cases: idle and loading represent simple states.
  • Associated value: success(String) stores a message, while failure(Int) stores an error code.
  • Pattern matching: A switch can extract associated data using case .success(let message).
  • Exhaustiveness: A switch over an enum must handle every possible case or provide default.
  • Raw values: enum Direction: String { case north = "N" } assigns a fixed string to a case.
  • Safety: An enum prevents invalid arbitrary states that might occur when plain strings or integers are used.

XI. Early Validation — Controlled Function Exit

Swift’s guard statement verifies required conditions and exits the current scope when those conditions are false.

A. Guard

A guard statement keeps the successful path unindented and is especially useful for validating optionals and function arguments.

SWIFT
func greet(name: String?) {
    guard let validName = name, !validName.isEmpty else {
        return
    }

    print("Hello, \(validName)")
}
  • Condition: guard let unwraps name, while !validName.isEmpty rejects an empty string.
  • Mandatory exit: The else block must transfer control with return, throw, break, or continue.
  • Extended scope: After the guard succeeds, validName remains available for the rest of the function.
  • Readable flow: Invalid input is handled early, avoiding deeply nested if statements.
  • Error propagation: A throwing function may use guard condition else { throw SomeError.invalidInput }.
  • Limitation: guard is appropriate only when failure should leave the current scope; ordinary two-way decisions usually require if or switch.