Unit 1: Introduction to iPhone and iOS Platform with Swift
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.
-
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.
-
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,
Vehiclemay definespeedandaccelerate(). - 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.
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 BankAccountintroduces the new reference type. - Stored property:
balancestores aDouble;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: BankAccountdeclaresBankAccountas 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.
var score: Int = 10
score = 15
let applicationName = "Weather"- Mutability:
scoremay change because it usesvar;applicationNamecannot be reassigned because it useslet. - Type annotation:
: Intexplicitly states the type. - Type inference: Swift infers
applicationNameasStringfrom its initial value. - Type safety: Assigning
"high"toscoreis invalid because aStringis not anInt. - 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 ornil, representing the absence of a value.
B. Arrays
An array is an ordered, zero-indexed collection whose elements normally have the same type.
var cities: [String] = ["Delhi", "Chennai"]
cities.append("Mumbai")
let firstCity = cities[0]- Type:
[String]is shorthand forArray<String>. - Ordering: Elements retain their sequence; index
0refers to"Delhi". - Mutation: A variable array supports
append,insert,remove, and element replacement. - Bounds: Accessing an index outside
0..<cities.countcauses a runtime error. - Iteration:
for city in citiesprocesses each element without manual index management. - Safe access: Properties such as
firstreturn 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.
class Lamp {
var isOn = false
func switchOn() {
isOn = true
}
}
let lamp = Lamp()
lamp.switchOn()- Instance method:
switchOn()operates on the instance referenced bylamp. - Call syntax:
lamp.switchOn()invokes the method using dot notation. - Parameters:
func move(to position: Int)receives a labelled argument throughmove(to: 5). - Return value:
func status() -> Booldeclares that the method returns a Boolean. - Type method: A method marked
staticbelongs 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.
let numbers = [3, 1, 2]
let sortedNumbers = numbers.sorted { first, second in
first < second
}- Closure expression:
{ first, second in first < second }supplies comparison behaviour tosorted. - Parameters:
firstandsecondare inferred asInt. - Return value: The Boolean expression indicates whether
firstshould precedesecond. - Type form:
(Int, Int) -> Boolmeans twoIntparameters produce aBool. - 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:
@escapingis 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.
var marks: [String: Int] = [
"Asha": 90,
"Ravi": 84
]
marks["Ravi"] = 88
let ashaMark = marks["Asha"]- Type:
[String: Int]mapsStringkeys toIntvalues. - Unique keys:
"Asha"can identify only one current value. - Optional lookup:
marks["Asha"]returnsInt?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"] = nilremoves the entry. - Iteration:
for (name, mark) in marksaccesses 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.
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
pointto 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.
enum NetworkState {
case idle
case loading
case success(String)
case failure(Int)
}
let state = NetworkState.success("Loaded")- Cases:
idleandloadingrepresent simple states. - Associated value:
success(String)stores a message, whilefailure(Int)stores an error code. - Pattern matching: A
switchcan extract associated data usingcase .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.
func greet(name: String?) {
guard let validName = name, !validName.isEmpty else {
return
}
print("Hello, \(validName)")
}- Condition:
guard letunwrapsname, while!validName.isEmptyrejects an empty string. - Mandatory exit: The
elseblock must transfer control withreturn,throw,break, orcontinue. - Extended scope: After the guard succeeds,
validNameremains available for the rest of the function. - Readable flow: Invalid input is handled early, avoiding deeply nested
ifstatements. - Error propagation: A throwing function may use
guard condition else { throw SomeError.invalidInput }. - Limitation:
guardis appropriate only when failure should leave the current scope; ordinary two-way decisions usually requireiforswitch.
Did this save you a night before the exam?
LPU Notes is free, and it stays free. Ads cover part of the server bill. The rest comes out of a student's own pocket: the domain, the storage, and keeping the site up through the weeks everyone needs it at once.
The payment button didn't load. An ad blocker or a filtered network is the usual reason. to try again.
Nothing here is ever locked, and nothing unlocks. Chip in only if it was worth it. What it pays for →