Unit 1: Introduction to iPhone and iOS Platform with Swift - Subjective Questions
INT372 — Iphone Application Programming • Practice Questions with Detailed Answers
20 questions
Distinguish between iOS and macOS with respect to their purpose, user interface, hardware support, and application development.
iOS and macOS are operating systems developed by Apple, but they serve different platforms.
- Purpose: iOS is designed primarily for mobile devices, while macOS is designed for desktop and laptop computers.
- Supported devices: iOS runs on devices such as the iPhone, whereas macOS runs on MacBook, iMac, Mac mini, and Mac Studio systems.
- User interface: iOS uses a touch-oriented interface with gestures such as tapping, swiping, and pinching. macOS primarily uses a keyboard, mouse, or trackpad.
- Application framework: iOS applications commonly use UIKit or SwiftUI. macOS applications commonly use AppKit or SwiftUI.
- Application distribution: iOS applications are generally distributed through the App Store and operate under strict sandboxing. macOS also supports the App Store but allows applications to be installed from other trusted sources.
- File access: iOS provides limited, sandboxed file-system access, whereas macOS gives users and applications broader file-system access.
- Multitasking: macOS supports a desktop-style multiwindow environment. iOS uses a mobile-oriented application lifecycle and more restricted background execution.
Both operating systems share technologies such as the Darwin core, Swift, Objective-C, Xcode, and several Apple development frameworks.
Explain the major features of the iOS platform and describe the tools commonly used to develop an iPhone application.
The iOS platform provides the operating environment, frameworks, and services required to build applications for Apple mobile devices.
Major features include:
- A touch-based interface with support for gestures and multitouch input.
- Application sandboxing and code signing for security.
- Frameworks for graphics, animation, networking, media, location, notifications, and data storage.
- Memory and resource management suited to mobile hardware.
- Accessibility, localization, and privacy services.
- A managed application lifecycle with foreground, inactive, background, and suspended states.
Development tools include:
- Xcode: Apple's integrated development environment used to write, build, test, and debug applications.
- Swift: A safe, expressive, and strongly typed programming language used for Apple-platform development.
- iOS SDK: A collection of frameworks, libraries, APIs, and development utilities.
- Simulator: A tool for running and testing applications on simulated Apple devices.
- Interface Builder: A visual tool within Xcode for constructing interfaces with storyboards and XIB files.
- Instruments: A performance-analysis tool used to identify memory, CPU, energy, and responsiveness problems.
A physical iPhone is also important for verifying behavior that cannot be represented completely by the Simulator, such as camera input, battery usage, and some hardware-specific features.
Define object-oriented programming and explain its main principles with reference to Swift.
Object-oriented programming (OOP) is a programming approach in which software is organized around objects that contain data and behavior. In Swift, classes are commonly used to create objects.
The main OOP principles are:
- Encapsulation: Data and related methods are grouped within a type. Access-control modifiers such as
private,internal, andpublicrestrict access to implementation details. - Abstraction: A type exposes essential behavior while hiding unnecessary implementation details. Protocols are frequently used to define abstractions in Swift.
- Inheritance: A class can inherit properties and methods from another class. The derived class can extend or override inherited behavior.
- Polymorphism: Different objects can be treated through a common superclass or protocol while providing their own implementations of behavior.
For example, Car and Bike can conform to a Vehicle protocol and implement a move() method differently. Calling move() through a Vehicle reference demonstrates polymorphism.
Describe how a class is declared and instantiated in Swift. Include properties, an initializer, and an instance method in your explanation.
A class is declared using the class keyword. Its definition may contain stored properties, computed properties, initializers, and methods.
Example:
class Student {
var name: String
var rollNumber: Int
init(name: String, rollNumber: Int) {
self.name = name
self.rollNumber = rollNumber
}
func displayDetails() -> String {
return "Name: \(name), Roll Number: \(rollNumber)"
}
}
let student = Student(name: "Anita", rollNumber: 12)
let details = student.displayDetails()Studentis the class name.nameandrollNumberare stored instance properties.initinitializes a new object and ensures that all non-optional stored properties receive values.selfrefers to the current instance.displayDetails()is an instance method.Student(name:rollNumber:)invokes the initializer and creates an instance.
Because a class is a reference type, multiple variables can refer to the same instance.
Explain inheritance, method overriding, and reference semantics in Swift classes with a suitable example.
Inheritance allows one class to acquire the properties and methods of another class. The original class is the superclass, and the inheriting class is the subclass. Swift supports single inheritance for classes.
class Vehicle {
var speed = 0
func description() -> String {
return "Speed: \(speed)"
}
}
class Car: Vehicle {
var numberOfDoors = 4
override func description() -> String {
return "Car speed: \(speed), doors: \(numberOfDoors)"
}
}Car: Vehicledeclares thatCarinherits fromVehicle.Carautomatically receives thespeedproperty.- The
overridekeyword indicates that the subclass replaces an inherited method implementation. - A subclass initializer may use
super.init()to initialize its superclass portion.
Classes have reference semantics. Therefore, assigning a class instance to another variable does not create an independent copy:
let first = Car()
let second = first
second.speed = 80After this code, both first.speed and second.speed are 80 because both constants refer to the same object. Identity operators === and !== can determine whether two references point to the same instance.
Differentiate between variables declared using var and constants declared using let in Swift. Also explain type inference and type annotation.
Swift uses var to declare a variable and let to declare a constant.
- A value stored in a
vardeclaration can be changed after initialization. - A value stored in a
letdeclaration cannot be reassigned after initialization. - Using
letis preferred when a value is not expected to change because it communicates intent and prevents accidental reassignment.
var score = 10
score = 20
let maximumScore = 100Type inference means Swift determines a value's type from its initial value. In var score = 10, Swift infers that score is an Int.
Type annotation explicitly states the expected type:
var temperature: Double = 28.5
let courseName: String = "Swift Programming"Swift is strongly typed, so a variable cannot later receive a value of an incompatible type. For example, an Int variable cannot be assigned a String. A declaration without an initial value generally requires a type annotation, such as var total: Int.
Explain optionals and optional binding in Swift. Why are optionals important in iPhone application development?
An optional represents either a value of a specified type or the absence of a value. Its type is written using ?, such as String?.
var userName: String? = "Meera"
userName = nilOptionals are important because many operations may not produce a value. Examples include finding an element, converting invalid text to a number, reading missing data, or accessing an interface element that is not currently available.
Optional binding safely extracts an optional value:
if let name = userName {
print(name)
} else {
print("Name is unavailable")
}Other handling techniques include:
guard letfor early exit when a value is absent.- The nil-coalescing operator
??for supplying a default value. - Optional chaining with
?.for accessing a property or method only when a value exists. - Forced unwrapping with
!, which should be used only when the value is guaranteed to exist because unwrappingnilcauses a runtime error.
Optionals make the possibility of missing data explicit and encourage safe handling at compile time.
Describe the creation, access, modification, traversal, and common operations of an array in Swift.
An array is an ordered collection of values of the same type. Arrays may contain duplicate values and use zero-based integer indexes.
var fruits: [String] = ["Apple", "Mango", "Orange"]Common operations:
- Access an element:
fruits[0] - Add an element:
fruits.append("Banana") - Insert an element:
fruits.insert("Grape", at: 1) - Modify an element:
fruits[0] = "Guava" - Remove an element:
fruits.remove(at: 2) - Count elements:
fruits.count - Test emptiness:
fruits.isEmpty - Check membership:
fruits.contains("Mango")
An array can be traversed using a loop:
for fruit in fruits {
print(fruit)
}Indexes must be validated before subscripting because accessing an index outside 0..<fruits.count causes a runtime error. An empty array can be created as [String]() or [] when its type is known from context.
Compare arrays and dictionaries in Swift. State suitable situations for using each collection.
Arrays and dictionaries are collection types, but they organize and retrieve data differently.
Array:
- Stores values in an ordered sequence.
- Uses zero-based integer indexes.
- Allows duplicate elements.
- Is suitable when order matters or elements are naturally processed sequentially.
- Example: a list of messages displayed in chronological order.
Dictionary:
- Stores key-value pairs.
- Uses unique hashable keys rather than positional indexes.
- Does not provide a meaningful application-level ordering unless explicitly sorted for presentation.
- Is suitable when a value must be found using an identifier.
- Example: looking up a student's mark by student ID.
let names = ["Asha", "Ravi"]
let marks = ["Asha": 85, "Ravi": 90]Use an array for ordered, index-based data. Use a dictionary for key-based lookup. Both collections are generic and type-safe, meaning the compiler verifies the types of their elements.
Define a method in Swift and distinguish among instance methods, type methods, mutating methods, and method parameters.
A method is a function associated with a class, structure, or enumeration.
- Instance method: Operates on a particular instance and can access its instance properties. It is declared using
func. - Type method: Belongs to the type itself rather than to an instance. It is declared with
static func; classes may useclass funcwhen subclasses should be allowed to override it. - Mutating method: A structure or enumeration method that changes
selfor an instance property. It must use themutatingkeyword. - Method parameters: Inputs accepted by a method. Swift methods can use argument labels and parameter names.
struct Counter {
var value = 0
mutating func increment(by amount: Int) {
value += amount
}
static func initialValue() -> Int {
return 0
}
}Here, increment(by:) is a mutating instance method. by is its argument label, amount is its parameter name, and initialValue() is a type method called as Counter.initialValue().
What is meant by sending a message to an object? Explain how this idea relates to method calls and dynamic dispatch in Swift.
In object-oriented terminology, sending a message means requesting an object to perform an operation. The message identifies the required behavior and may carry arguments. In Swift, this is normally expressed as a method call.
account.deposit(amount: 500)In this expression:
accountis the receiver.depositidentifies the requested operation.amount: 500supplies an argument.- The
Accounttype determines which method is available and how the request is handled.
With polymorphism, the implementation selected at runtime may depend on the actual object. For example, a variable typed as a superclass can hold a subclass instance. Calling an overridden method through that variable invokes the subclass implementation through dynamic dispatch.
Message-based interaction supports encapsulation because callers ask an object to perform behavior instead of directly manipulating its private representation. In current Swift terminology, developers usually say that a method is invoked, while the message concept explains the underlying OOP interaction.
Define a closure in Swift and explain its syntax, parameters, return values, and type inference with an example.
A closure is a self-contained block of executable code that can be stored in a variable, passed to a function, or returned from a function. Functions are a special form of closure in Swift.
General closure syntax:
{ (parameters) -> ReturnType in
statements
}Example:
let multiply: (Int, Int) -> Int = { (first: Int, second: Int) -> Int in
return first * second
}
let result = multiply(4, 5)The closure accepts two Int values and returns an Int. Because Swift can infer types from context, it can be shortened:
let multiply: (Int, Int) -> Int = { $0 * $1 }- The
inkeyword separates parameters and the return type from the body. $0and$1are shorthand argument names.- A single-expression closure can omit
return. - The closure type
(Int, Int) -> Intdescribes its input and output types.
Closures are frequently used by collection methods and asynchronous iOS APIs.
Explain trailing closures, value capture, and escaping closures in Swift. Discuss one memory-management risk associated with closures.
A trailing closure is written after a function's parentheses when a closure is the final argument. If it is the only argument, the parentheses may be omitted.
let sortedNames = names.sorted { first, second in
first < second
}Value capture means that a closure can refer to variables and constants from its surrounding scope. The closure preserves access to those captured values even if the original scope has ended.
An escaping closure can be stored or executed after the function that received it has returned. Its parameter must be marked with @escaping:
func loadData(completion: @escaping (String) -> Void) {
// Store or invoke completion asynchronously.
}Escaping completion handlers are common in asynchronous networking and animation APIs.
A memory-management risk occurs when an object strongly owns a closure and that closure strongly captures the same object through self. This creates a strong reference cycle. A capture list can break the cycle:
service.load { [weak self] result in
self?.handle(result)
}Using [weak self] makes the captured reference optional and allows the object to be deallocated. [unowned self] may be used only when self is guaranteed to remain alive while the closure executes.
Describe how to declare, access, update, remove, and iterate over entries in a Swift dictionary.
A dictionary stores associations between unique keys and values. All keys must have the same type, all values must have the same type, and the key type must conform to Hashable.
var marks: [String: Int] = ["Asha": 88, "Ravi": 91]Common operations:
- Access a value:
marks["Asha"] - Add or replace a value:
marks["Meena"] = 84 - Update and obtain the old value:
marks.updateValue(95, forKey: "Ravi") - Remove a value:
marks["Asha"] = nil - Remove and obtain the old value:
marks.removeValue(forKey: "Ravi") - Count entries:
marks.count - Test emptiness:
marks.isEmpty
Dictionary subscripting returns an optional because the requested key may not exist:
if let mark = marks["Meena"] {
print(mark)
}Iteration can access each key-value pair:
for (student, mark) in marks {
print("\(student): \(mark)")
}When a stable presentation order is required, the keys or key-value pairs should be explicitly sorted.
Define a structure in Swift and compare structures with classes in terms of semantics, inheritance, initialization, and usage.
A structure, declared with struct, is a custom type that can contain properties, initializers, methods, subscripts, and protocol conformances.
struct Point {
var x: Double
var y: Double
}Comparison with classes:
- Semantics: Structures are value types, so assignment and parameter passing conceptually create independent values. Classes are reference types, so multiple references can point to the same instance.
- Inheritance: Classes support inheritance; structures do not inherit from other structures or classes.
- Initialization: Structures automatically receive a memberwise initializer when appropriate. Classes do not receive an automatic memberwise initializer.
- Identity: Class instances can be compared for identity using
===; structure values have no object identity. - Deinitialization: Classes can define
deinit; structures cannot. - Mutation: A structure method that changes a property must be marked
mutating. A structure stored in aletconstant cannot have its variable properties changed.
Structures are generally preferred for small data models, independent values, and types that do not require inheritance or shared identity. Classes are appropriate when identity, shared mutable state, inheritance, or deinitialization is required.
Explain value semantics using a Swift structure and contrast the result with assigning a class instance.
Value semantics means that each variable holds an independent value. Assigning a structure to another variable conceptually copies that value.
struct Location {
var city: String
}
var first = Location(city: "Chennai")
var second = first
second.city = "Madurai"After this code:
first.cityremains"Chennai".second.citybecomes"Madurai".- Changing
seconddoes not changefirst.
A class behaves differently:
class LocationBox {
var city: String
init(city: String) {
self.city = city
}
}
let firstBox = LocationBox(city: "Chennai")
let secondBox = firstBox
secondBox.city = "Madurai"Now both references report "Madurai" because they point to the same instance. Value semantics make local reasoning easier and reduce accidental shared mutation. Swift's standard types, including String, Array, and Dictionary, are value types, although collections may use copy-on-write internally for efficiency.
Define an enumeration in Swift. Explain raw values, associated values, methods, and pattern matching.
An enumeration, declared using enum, defines a common type for a finite set of related cases.
A raw-value enumeration gives every case a predefined value of the same type:
enum Direction: String {
case north = "N"
case south = "S"
case east = "E"
case west = "W"
}An associated-value enumeration stores additional data that can differ for each instance:
enum NetworkResult {
case success(data: String)
case failure(code: Int, message: String)
}Associated values are extracted through pattern matching:
switch result {
case .success(let data):
print(data)
case .failure(let code, let message):
print("\(code): \(message)")
}Enumerations can also contain computed properties, initializers, and methods. Raw values and associated values serve different purposes: raw values are fixed values defined for cases, whereas associated values are supplied when an enum instance is created. Swift's exhaustive switch statement ensures that every possible case is handled unless a default case is used.
Compare structs and enums in Swift and explain when an enum is preferable to a struct.
Both structs and enums are value types. They can define properties, initializers, methods, subscripts, extensions, and protocol conformances. Assignment creates independent values under value semantics.
A struct represents a value composed of several fields that may all exist at the same time. For example, a User struct can contain a name, email address, and age.
An enum represents one case from a finite set of alternatives. Each case may carry different associated data. For example:
enum ScreenState {
case loading
case loaded(items: [String])
case failed(message: String)
}An enum is preferable when:
- The value must be exactly one of several known states.
- Different states need different associated information.
- Exhaustive handling through
switchis useful. - Invalid combinations of flags or optional properties should be prevented.
A struct is preferable when the model consists of a stable group of properties that coexist. An enum often models application state more safely because it makes impossible states difficult or impossible to represent.
Explain the purpose and syntax of the guard statement in Swift. Compare guard with if for validating conditions.
The guard statement checks that a condition required for continued execution is true. When the condition is false, the else block must transfer control out of the current scope using return, break, continue, or throw.
func greet(name: String?) {
guard let name = name, !name.isEmpty else {
return
}
print("Hello, \(name)")
}Characteristics of guard:
- It supports early exit when a requirement is not satisfied.
- It reduces deeply nested conditional code.
- Values created through
guard letremain available after the statement in the surrounding scope. - Multiple Boolean and optional-binding conditions can be separated by commas.
Comparison with if:
ifexecutes a block when a condition is true and is useful for branching or handling local conditional behavior.guardemphasizes mandatory preconditions and handles failure first.- A value bound with
if letnormally remains available only inside theifblock, whereas a value bound withguard letis available after the guard statement.
Thus, guard is particularly useful for validating function parameters and required application state.
Design and explain a Swift model that combines a class or struct, enum, array, dictionary, closure, method, and guard statement for a simple iPhone course-registration feature.
A course-registration model can combine the unit's concepts as follows:
enum RegistrationError: Error {
case invalidStudent
case courseNotFound
case alreadyRegistered
}
struct Course {
let code: String
var students: [String]
}
class RegistrationManager {
private var courses: [String: Course] = [:]
func addCourse(_ course: Course) {
courses[course.code] = course
}
func register(
student: String,
for courseCode: String,
completion: (Result<Course, RegistrationError>) -> Void
) {
guard !student.isEmpty else {
completion(.failure(.invalidStudent))
return
}
guard var course = courses[courseCode] else {
completion(.failure(.courseNotFound))
return
}
guard !course.students.contains(student) else {
completion(.failure(.alreadyRegistered))
return
}
course.students.append(student)
courses[courseCode] = course
completion(.success(course))
}
}Explanation:
Courseis a struct because it represents an independent data value.RegistrationManageris a class that manages shared registration state.RegistrationErroris an enum representing a finite set of failure cases.studentsis an array that stores an ordered collection of names.coursesis a dictionary that provides lookup by course code.register(student:for:completion:)is a method containing the registration behavior.- The
completionparameter is a closure that reports success or failure. - The
guardstatements validate the student name, course existence, and duplicate-registration rule using early exits.
This design uses strong typing and explicit states to prevent ambiguous results and centralizes registration rules in one manager.
Distinguish between iOS and macOS with respect to their purpose, user interface, hardware support, and application development.
iOS and macOS are operating systems developed by Apple, but they serve different platforms.
- Purpose: iOS is designed primarily for mobile devices, while macOS is designed for desktop and laptop computers.
- Supported devices: iOS runs on devices such as the iPhone, whereas macOS runs on MacBook, iMac, Mac mini, and Mac Studio systems.
- User interface: iOS uses a touch-oriented interface with gestures such as tapping, swiping, and pinching. macOS primarily uses a keyboard, mouse, or trackpad.
- Application framework: iOS applications commonly use UIKit or SwiftUI. macOS applications commonly use AppKit or SwiftUI.
- Application distribution: iOS applications are generally distributed through the App Store and operate under strict sandboxing. macOS also supports the App Store but allows applications to be installed from other trusted sources.
- File access: iOS provides limited, sandboxed file-system access, whereas macOS gives users and applications broader file-system access.
- Multitasking: macOS supports a desktop-style multiwindow environment. iOS uses a mobile-oriented application lifecycle and more restricted background execution.
Both operating systems share technologies such as the Darwin core, Swift, Objective-C, Xcode, and several Apple development frameworks.
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 →