Unit 1 subjective questions Introduction to iPhone and iOS Platform with Swift
INT372 — Iphone Application Programming 20 questions with model answers. Write yours first, then compare.
-
Question 1 of 20
Distinguish between iOS and macOS with respect to their purpose, user interface, hardware support, and application development.
Model answer
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.
-
Question 2 of 20
Explain the major features of the iOS platform and describe the tools commonly used to develop an iPhone application.
Model answer
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.
-
Question 3 of 20
Define object-oriented programming and explain its main principles with reference to Swift.
Model answer
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,
CarandBikecan conform to aVehicleprotocol and implement amove()method differently. Callingmove()through aVehiclereference demonstrates polymorphism. - Encapsulation: Data and related methods are grouped within a type. Access-control modifiers such as
-
Question 4 of 20
Describe how a class is declared and instantiated in Swift. Include properties, an initializer, and an instance method in your explanation.
Model answer
A class is declared using the
classkeyword. Its definition may contain stored properties, computed properties, initializers, and methods.Example:
Swiftclass 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.
-
Question 5 of 20
Explain inheritance, method overriding, and reference semantics in Swift classes with a suitable example.
Model answer
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.
Swiftclass 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:
Swiftlet first = Car() let second = first second.speed = 80After this code, both
first.speedandsecond.speedare80because both constants refer to the same object. Identity operators===and!==can determine whether two references point to the same instance. -
-
Question 6 of 20
Differentiate between variables declared using
varand constants declared usingletin Swift. Also explain type inference and type annotation.Model answer
Swift uses
varto declare a variable andletto 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.
Swiftvar 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 thatscoreis anInt.Type annotation explicitly states the expected type:
Swiftvar 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
Intvariable cannot be assigned aString. A declaration without an initial value generally requires a type annotation, such asvar total: Int. - A value stored in a
-
Question 7 of 20
Explain optionals and optional binding in Swift. Why are optionals important in iPhone application development?
Model answer
An optional represents either a value of a specified type or the absence of a value. Its type is written using
?, such asString?.Swiftvar 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:
Swiftif 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.
-
Question 8 of 20
Describe the creation, access, modification, traversal, and common operations of an array in Swift.
Model answer
An array is an ordered collection of values of the same type. Arrays may contain duplicate values and use zero-based integer indexes.
Swiftvar 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:
Swiftfor fruit in fruits { print(fruit) }Indexes must be validated before subscripting because accessing an index outside
0..<fruits.countcauses a runtime error. An empty array can be created as[String]()or[]when its type is known from context. - Access an element:
-
Question 9 of 20
Compare arrays and dictionaries in Swift. State suitable situations for using each collection.
Model answer
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.
Swiftlet 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.
-
Question 10 of 20
Define a method in Swift and distinguish among instance methods, type methods, mutating methods, and method parameters.
Model answer
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.
Swiftstruct 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.byis its argument label,amountis its parameter name, andinitialValue()is a type method called asCounter.initialValue(). - Instance method: Operates on a particular instance and can access its instance properties. It is declared using
-
Question 11 of 20
What is meant by sending a message to an object? Explain how this idea relates to method calls and dynamic dispatch in Swift.
Model answer
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.
Swiftaccount.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.
-
Question 12 of 20
Define a closure in Swift and explain its syntax, parameters, return values, and type inference with an example.
Model answer
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:
Swift{ (parameters) -> ReturnType in statements }Example:
Swiftlet multiply: (Int, Int) -> Int = { (first: Int, second: Int) -> Int in return first * second } let result = multiply(4, 5)The closure accepts two
Intvalues and returns anInt. Because Swift can infer types from context, it can be shortened:Swiftlet 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.
- The
-
Question 13 of 20
Explain trailing closures, value capture, and escaping closures in Swift. Discuss one memory-management risk associated with closures.
Model answer
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.
Swiftlet 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:Swiftfunc 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:Swiftservice.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 whenselfis guaranteed to remain alive while the closure executes. -
Question 14 of 20
Describe how to declare, access, update, remove, and iterate over entries in a Swift dictionary.
Model answer
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.Swiftvar 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:
Swiftif let mark = marks["Meena"] { print(mark) }Iteration can access each key-value pair:
Swiftfor (student, mark) in marks { print("\(student): \(mark)") }When a stable presentation order is required, the keys or key-value pairs should be explicitly sorted.
- Access a value:
-
Question 15 of 20
Define a structure in Swift and compare structures with classes in terms of semantics, inheritance, initialization, and usage.
Model answer
A structure, declared with
struct, is a custom type that can contain properties, initializers, methods, subscripts, and protocol conformances.Swiftstruct 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.
-
Question 16 of 20
Explain value semantics using a Swift structure and contrast the result with assigning a class instance.
Model answer
Value semantics means that each variable holds an independent value. Assigning a structure to another variable conceptually copies that value.
Swiftstruct 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:
Swiftclass 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, includingString,Array, andDictionary, are value types, although collections may use copy-on-write internally for efficiency. -
Question 17 of 20
Define an enumeration in Swift. Explain raw values, associated values, methods, and pattern matching.
Model answer
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:
Swiftenum 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:
Swiftenum NetworkResult { case success(data: String) case failure(code: Int, message: String) }Associated values are extracted through pattern matching:
Swiftswitch 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
switchstatement ensures that every possible case is handled unless adefaultcase is used. -
Question 18 of 20
Compare structs and enums in Swift and explain when an enum is preferable to a struct.
Model answer
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
Userstruct 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:
Swiftenum 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.
-
Question 19 of 20
Explain the purpose and syntax of the
guardstatement in Swift. Compareguardwithiffor validating conditions.Model answer
The
guardstatement checks that a condition required for continued execution is true. When the condition is false, theelseblock must transfer control out of the current scope usingreturn,break,continue, orthrow.Swiftfunc 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,
guardis particularly useful for validating function parameters and required application state. -
Question 20 of 20
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.
Model answer
A course-registration model can combine the unit's concepts as follows:
Swiftenum 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.
That's unit 1
Long answers stick best when they're tested again soon. Run the MCQs on this unit, then come back to the questions you found hardest.
Nearly through. Did unit 1 of INT372 save you a night before the exam?
LPU Notes is free. A student pays for the servers.
Did unit 1 of INT372 save you a night before the exam?
Then you can help keep it free for the next batch. 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.