Top Interview Questions
iOS is a mobile operating system developed by Apple Inc., specifically designed to run on Apple hardware, including the iPhone, iPad, and iPod Touch. Known for its intuitive interface, robust security, and seamless integration with the Apple ecosystem, iOS has grown to become one of the most influential mobile operating systems globally. It combines performance, design, and functionality in a way that appeals to millions of users and developers worldwide.
iOS, originally named iPhone OS, was first introduced in 2007 alongside the first iPhone. At that time, smartphones were dominated by BlackBerry OS, Symbian, and Windows Mobile. Apple revolutionized the mobile industry by providing a touchscreen-based interface without a physical keyboard, coupled with an operating system that was optimized for touch interactions.
Over the years, Apple rebranded iPhone OS as iOS in 2010 with the release of iOS 4. This rebranding coincided with several key innovations, such as multitasking, FaceTime, and the introduction of the iPad as a major device in Apple’s portfolio. iOS has since gone through numerous iterations, each improving performance, enhancing user experience, and introducing new features like Siri (iOS 5), Control Center (iOS 7), Dark Mode (iOS 13), and more recently, advanced AI-powered features and system-wide enhancements.
iOS is built on a layered architecture that ensures reliability, security, and efficiency. Its architecture can be broadly divided into four layers:
Cocoa Touch Layer:
This is the topmost layer that provides frameworks for building applications. Cocoa Touch offers essential APIs for touch-based input, gestures, multitasking, notifications, and high-level services like camera and location. It is primarily used by developers to design interactive applications that adhere to Apple’s human interface guidelines.
Media Layer:
The Media layer provides graphics, audio, and video support. It includes technologies like Core Graphics, Core Animation, Core Image, AVFoundation, and OpenGL/Metal for 3D graphics. This layer allows developers to create visually appealing and media-rich applications while ensuring efficient rendering and performance.
Core Services Layer:
This layer provides fundamental services and data management capabilities. Key components include Core Data for database management, Foundation framework for standard utilities, and CloudKit for iCloud integration. Core Services also handles networking, threading, and other system-level services that ensure apps can run smoothly.
Core OS Layer:
The Core OS layer interacts directly with the device hardware. It includes the kernel, device drivers, and low-level features like security, file system management, networking, and power management. This layer ensures that iOS runs securely and efficiently on Apple devices.
This layered architecture allows iOS to provide a balance of performance, user experience, and security, which is critical for mobile devices with limited resources compared to desktop computers.
iOS is distinguished by several unique features that make it stand out among mobile operating systems:
iOS is renowned for its clean, intuitive, and user-friendly interface. The operating system follows strict Human Interface Guidelines (HIG), which provide consistency across apps. Features like the home screen, dock, gestures, and animations create a seamless and responsive user experience.
Apple’s App Store is the primary distribution platform for iOS apps. It provides a secure and curated environment for users to download applications. Developers benefit from a large audience and monetization opportunities through app purchases, subscriptions, and in-app purchases. The App Store has millions of apps covering productivity, gaming, education, and entertainment.
Security is a cornerstone of iOS. Apple implements features like Data Encryption, Secure Boot, App Sandbox, Face ID, and Touch ID to protect user data. iOS also enforces strict app review policies to prevent malicious applications from entering the App Store. Features like privacy labels, permission prompts, and on-device processing for AI tasks further enhance user privacy.
iOS devices seamlessly integrate with other Apple products and services. Features like Handoff, Continuity, AirDrop, and iCloud allow users to switch devices effortlessly, share files, and maintain synchronized data across multiple devices. This integration creates a cohesive experience that enhances productivity and convenience.
Siri, Apple’s virtual assistant, is integrated deeply into iOS. It enables voice commands, smart suggestions, and automation through Shortcuts. With each iOS iteration, Siri has grown smarter, offering natural language understanding, proactive suggestions, and integration with third-party apps.
Apple provides regular updates for iOS, often supporting devices for up to five to six years. This long-term support ensures that users receive new features, security patches, and performance improvements without needing to purchase a new device. This approach contrasts with many other mobile operating systems that provide shorter support cycles.
iOS development involves creating applications using Apple’s programming languages and frameworks. Key aspects include:
Objective-C: One of the original languages used for iOS development. It is a superset of C, offering object-oriented features.
Swift: Introduced in 2014, Swift is a modern programming language designed to be safe, fast, and expressive. It is now the preferred language for iOS development.
iOS apps are primarily developed using Xcode, Apple’s integrated development environment (IDE). Xcode provides tools for designing user interfaces, coding, debugging, and testing apps. The IDE also includes a simulator to test apps on different device configurations.
Developers use various frameworks provided by Apple, including:
UIKit: For building user interfaces.
Core Data: For data persistence.
AVFoundation: For audio and video.
Core ML: For machine learning integration.
ARKit: For augmented reality experiences.
iOS apps go through a defined lifecycle, including states like Not Running, Inactive, Active, Background, and Suspended. Understanding this lifecycle is crucial for optimizing performance and resource management.
Once an app is ready, developers submit it to the App Store for review. Apple’s review process ensures compliance with guidelines and security standards before an app becomes publicly available.
iOS runs on a range of Apple devices, including:
iPhone: The flagship mobile device for which iOS was originally developed.
iPad: iPads run a variant of iOS called iPadOS, optimized for larger screens and multitasking.
iPod Touch: A portable media player and gaming device.
Apple Watch (watchOS) and Apple TV (tvOS): While technically running distinct operating systems, they share many frameworks and design principles with iOS.
Consistent User Experience: Apple’s strict design guidelines ensure that users enjoy a consistent and smooth experience across all devices.
Security: Strong encryption, regular updates, and app review processes reduce the risk of malware and data breaches.
High Performance: iOS is optimized for Apple hardware, resulting in fast and responsive devices.
Longevity: Devices receive software updates for many years, ensuring longevity and reduced e-waste.
Developer Support: Comprehensive tools, documentation, and frameworks make it easier for developers to create high-quality apps.
Despite its strengths, iOS faces some criticisms:
Closed Ecosystem: iOS restricts app installations to the App Store, limiting flexibility for users who want more control.
Hardware Dependency: iOS can only run on Apple devices, which are often expensive compared to alternatives.
Customization Limitations: Unlike Android, iOS allows limited customization of the user interface.
Answer:
iOS is Apple’s mobile operating system used in iPhone, iPad, and iPod Touch devices. It is built on the Darwin kernel and provides a smooth user interface, security features, and performance optimization. iOS supports applications developed using Swift or Objective-C.
Answer:
Multitasking: Supports running multiple apps in the background.
User-friendly interface: Smooth touch gestures and simple UI design.
Security: Data protection with encryption and app sandboxing.
Regular updates: Apple frequently releases new iOS versions.
App Store: Centralized platform for app distribution.
Performance: Optimized for Apple hardware ensuring smooth operation.
| Feature | iOS | Android |
|---|---|---|
| OS Type | Closed source | Open source |
| Programming | Swift / Objective-C | Java / Kotlin |
| App Store | App Store | Google Play Store |
| Customization | Limited | Highly customizable |
| Hardware | Only Apple devices | Multiple manufacturers |
| Updates | Released for all devices at once | Fragmented across devices |
Answer:
Swift: Modern, fast, and safe language designed by Apple.
Objective-C: Older language still used in legacy applications.
Answer:
Swift is Apple’s programming language introduced in 2014 for iOS, macOS, watchOS, and tvOS app development. It is safe, fast, and expressive and supports modern programming paradigms like object-oriented and functional programming.
| Feature | Swift | Objective-C |
|---|---|---|
| Syntax | Modern and clean | Older and verbose |
| Safety | Safe with null handling | Less safe |
| Speed | Faster | Slightly slower |
| Popularity | Increasing | Decreasing |
| Memory Management | Automatic Reference Counting (ARC) | ARC and manual options |
Answer:
Xcode is Apple’s Integrated Development Environment (IDE) used to develop iOS, macOS, watchOS, and tvOS applications.
Key Features:
Code editor
Interface builder
Simulator for testing apps
Debugging tools
Performance analysis tools
Answer:
MVC stands for Model-View-Controller, an architecture pattern used in iOS app development:
Model: Manages app data and business logic.
View: Displays the user interface.
Controller: Handles interactions between the Model and View.
Answer:
Storyboards are visual representations of the app’s user interface in Xcode. They show screens (view controllers) and their connections (segues).
Benefits:
Easy to design UI
Supports drag-and-drop interface elements
Helps visualize navigation flow
Answer:
A delegate is a design pattern in iOS used to communicate between objects. One object can delegate responsibilities to another object.
Example: UITableViewDelegate handles table view events like row selection.
frame and bounds in iOS?| Term | Description |
|---|---|
| Frame | The view’s size and position relative to its superview. |
| Bounds | The view’s size and position relative to itself. |
IBOutlet and IBAction?IBOutlet: Connects UI elements from storyboard to Swift code.
IBAction: Connects user actions (like button taps) to Swift functions.
Answer:
Auto Layout is a system that allows developers to create adaptive UI for different screen sizes and orientations. Constraints define relationships between UI elements to adjust layouts automatically.
weak and strong in Swift?| Term | Description |
|---|---|
| Strong | Keeps a reference to an object in memory. |
| Weak | Doesn’t prevent object from being deallocated; avoids retain cycles. |
Answer:
ARC (Automatic Reference Counting) manages memory in Swift and Objective-C. It automatically tracks and manages object lifetimes to prevent memory leaks.
Answer:
View Controllers manage a single screen in an app. They handle user interactions, update UI elements, and communicate with the model.
Types:
UIViewController – Base class
UITableViewController – For table views
UICollectionViewController – For collection views
Native App: Developed using Swift or Objective-C for iOS.
Hybrid App: Uses web technologies like HTML, CSS, and JavaScript wrapped in a native shell.
Web App: Accessed via the browser, not installed on the device.
frame and autoresizing?Frame: Absolute position of a view.
Autoresizing: Allows the view to resize automatically based on its parent view.
| Term | Description |
|---|---|
| Synchronous | Task runs in order, blocking the main thread until finished. |
| Asynchronous | Task runs in the background, doesn’t block main thread. |
Answer:
Core Data is a framework for managing object graphs and persisting data in iOS apps. It allows developers to store data in a database-like system without writing SQL queries.
frame and center in iOS?Frame: Position and size of the view.
Center: The point representing the center of the view.
nil and Optional in Swift?Optional: A variable that may or may not have a value.
Nil: Represents no value assigned to an optional variable.
Answer:
GCD is a framework for concurrent programming in iOS. It allows executing tasks asynchronously on different queues (main, background).
Example:
DispatchQueue.global().async {
// Background task
DispatchQueue.main.async {
// Update UI
}
}
weak, unowned, and strong references?Strong: Default, keeps object in memory.
Weak: Does not prevent deallocation, used in circular references.
Unowned: Similar to weak but assumes object always exists; crashes if object is nil.
Answer:
The iOS app life cycle represents the states an app goes through:
Not running: App not launched.
Inactive: App in foreground but not receiving events.
Active: App in foreground and running.
Background: App running in the background.
Suspended: App in memory but not executing code.
Answer:
Notifications allow apps to communicate asynchronously:
Local Notifications: Scheduled by the app itself.
Push Notifications: Sent by a server through APNs (Apple Push Notification service).
struct and class in Swift?| Feature | Struct | Class |
|---|---|---|
| Reference/Value type | Value type | Reference type |
| Inheritance | No | Yes |
| Memory | Stack | Heap |
| Mutability | var required |
Can modify properties |
frame and bounds?We already covered this, but to recap:
Frame: Relative to superview.
Bounds: Relative to the view itself.
UITableView and UICollectionView?UITableView: Single column, vertical scrolling list.
UICollectionView: Grid-based or custom layouts, more flexible.
let and var in Swift?Answer:
let: Declares a constant. Its value cannot be changed after initialization.
var: Declares a variable. Its value can be modified after initialization.
Example:
let name = "Yash" // constant
var age = 25 // variable
age = 26 // allowed
Answer:
A protocol defines a blueprint of methods, properties, and other requirements that suit a particular task. Classes, structs, or enums can adopt protocols.
Example:
protocol Drivable {
func drive()
}
class Car: Drivable {
func drive() {
print("Car is driving")
}
}
extension and subclass?| Feature | Extension | Subclass |
|---|---|---|
| Purpose | Adds functionality to existing class/struct | Creates a new class based on a parent class |
| Inheritance | Not required | Required |
| Access to properties | Limited to public/protected | Can access all properties of parent |
synchronous and asynchronous execution?Answer:
Synchronous: Blocks the current thread until the task completes.
Asynchronous: Runs in the background; allows UI and other tasks to continue.
Example with GCD:
DispatchQueue.global().async { // asynchronous
// background task
}
strong, weak, and unowned references in Swift?Answer:
Strong: Keeps a reference to an object; prevents deallocation.
Weak: Does not keep the object in memory; automatically becomes nil if object deallocates.
Unowned: Similar to weak but assumes object always exists; crashes if nil.
View and Layer?View: Displays UI and handles user interactions.
Layer: Core Animation layer responsible for rendering and animations; each view has an underlying layer.
UITableView and UICollectionView?UITableView: Vertical scrolling list with single-column cells.
UICollectionView: Flexible layout; supports grid, horizontal, and custom layouts.
frame, bounds, and center in iOS?| Term | Description |
|---|---|
| Frame | Position and size relative to superview |
| Bounds | Position and size relative to itself |
| Center | The center point of the view |
Answer:
NotificationCenter allows communication between objects in an app without tightly coupling them. It uses observers to listen for notifications.
Example:
NotificationCenter.default.addObserver(self, selector: #selector(update), name: Notification.Name("UpdateData"), object: nil)
push and modal view controllers?Push: Adds a view to the navigation stack. Back button appears.
Modal: Presents a new view controller over the current one. Usually requires dismissal.
weak self and unowned self in closures?Weak self: Prevents strong reference cycle; optional.
Unowned self: Prevents strong reference cycle; assumes self always exists (non-optional).
Answer:
Optionals allow a variable to hold a value or no value (nil). Useful to avoid crashes.
Example:
var name: String? = "Yash"
name = nil // valid
guard and if let in Swift?if let: Used to unwrap optionals conditionally.
guard let: Ensures a value exists; else executes early exit (return, break).
Example:
func process(name: String?) {
guard let unwrappedName = name else { return }
print(unwrappedName)
}
class and struct in Swift?| Feature | Class | Struct |
|---|---|---|
| Type | Reference | Value |
| Inheritance | Yes | No |
| Memory | Heap | Stack |
| Mutability | Can modify even in let | Requires var |
didSet and willSet?willSet: Called before a property changes.
didSet: Called after a property changes.
lazy and regular properties?lazy: Initialized only when first accessed. Useful for heavy objects.
regular: Initialized immediately when the instance is created.
App Sandbox and normal apps?Sandboxed app: Limited access to resources, files, and system. Ensures security.
Normal app: No restriction, can access files, resources freely (not in iOS, only conceptually).
MVC (Model-View-Controller): Apple default; separates data, UI, and logic.
MVVM (Model-View-ViewModel): Improves testing and code separation.
VIPER: Layered architecture for large apps.
Clean Architecture: Decouples presentation, domain, and data layers.
Main Thread and Background Thread?Main Thread: Handles UI and user interaction; must be fast.
Background Thread: Handles heavy tasks like network requests or DB operations.
Synchronous and Asynchronous network calls?| Feature | Synchronous | Asynchronous |
|---|---|---|
| Execution | Blocks until response | Runs in background |
| UI Impact | Freezes UI | UI stays responsive |
| Usage | Rare | Common (URLSession) |
Answer:
ABI Stability: Swift 5 introduced ABI (Application Binary Interface) stability for better compatibility.
Standard Library: Swift 5 includes a smaller, more stable standard library.
String Handling: Strings in Swift 5 support raw strings and improved Unicode support.
Result Type: Swift 5 introduces Result<T, Error> for cleaner error handling.
Answer:
iOS uses Automatic Reference Counting (ARC) to manage memory.
ARC keeps a count of strong references to objects; when the count reaches 0, the object is deallocated.
Strong references: Default; keep the object alive.
Weak references: Avoid retain cycles; do not increase reference count.
Unowned references: Similar to weak but non-optional; assumes object will not be nil.
Advanced Tip: Always break strong reference cycles in closures, delegates, and view controller hierarchies.
Answer:
Synchronous: Blocks the current thread; can freeze UI.
Asynchronous: Runs in background, allowing the main thread to stay responsive.
Implementation: Use GCD (DispatchQueue) or OperationQueue for asynchronous execution.
struct and class in Swift| Feature | Struct | Class |
|---|---|---|
| Type | Value type | Reference type |
| Inheritance | Not supported | Supported |
| Memory | Stack | Heap |
| Mutability | var required |
Can modify even in let |
| Deinitializers | Not supported | Supported |
Advanced Tip: Use structs for thread safety and immutability; use classes for shared mutable state.
Strong: Keeps object alive; default.
Weak: Prevents retain cycles; automatically becomes nil if object deallocated.
Unowned: Prevents retain cycles; assumes object exists; crashes if nil.
Example in closures:
class ViewController {
var closure: (() -> Void)?
func setup() {
closure = { [weak self] in
self?.doSomething()
}
}
}
Answer:
Model: Handles business logic and data.
View: UI components; only handles display.
ViewModel: Connects Model and View; processes data for the view.
Advantages over MVC:
Reduces massive view controllers.
Improves testability.
Supports reactive programming with Combine or RxSwift.
Answer:
Core Data is Apple’s object graph and persistence framework.
Stores data in SQLite or in-memory stores.
Optimization Tips:
Use fetch limits and batch size to reduce memory.
Avoid fetched properties for large datasets.
Use NSFetchedResultsController for table/collection view syncing.
Use background contexts for heavy operations.
Answer:
GCD: Framework for concurrent code execution.
Queues:
Main Queue: Serial; updates UI.
Global Queue: Concurrent; background tasks.
Custom Queue: Serial or concurrent for specific tasks.
Example:
DispatchQueue.global(qos: .background).async {
// background task
DispatchQueue.main.async {
// update UI
}
}
Optionals represent a value or nil.
Safe handling techniques:
Optional binding (if let, guard let)
Nil coalescing operator (??)
Optional chaining (object?.property)
Force unwrapping (!) – avoid in production
Example:
let name: String? = "Yash"
print(name ?? "No name")
Answer:
Combine is Apple’s reactive programming framework introduced in iOS 13.
Handles asynchronous events using publishers and subscribers.
Example:
import Combine
let publisher = [1,2,3].publisher
let subscriber = publisher.sink { value in
print(value)
}
Use Combine for network calls, UI updates, and state management.
Reduce unnecessary layout calculations.
Avoid heavy main thread operations.
Use lazy loading for images and data.
Cache resources using NSCache.
Profile using Instruments: CPU, Memory, and Time Profiler.
URLSession: Framework for making HTTP requests.
Supports data tasks, download tasks, and upload tasks.
Use background sessions for large downloads.
Always perform JSON decoding asynchronously.
Example:
let url = URL(string: "https://api.example.com")!
URLSession.shared.dataTask(with: url) { data, response, error in
guard let data = data else { return }
let json = try? JSONSerialization.jsonObject(with: data)
}.resume()
Avoid strong reference cycles in closures, delegates, and view controllers.
Use weak/unowned references appropriately.
Monitor memory using Instruments (Leaks, Allocations).
Release unused objects and cached resources.
SwiftUI is Apple’s declarative UI framework introduced in iOS 13.
Advantages:
Less boilerplate code than UIKit
Live previews in Xcode
Cross-platform (iOS, macOS, watchOS, tvOS)
Supports state management using @State, @Binding, @ObservedObject
Example:
struct ContentView: View {
@State private var counter = 0
var body: some View {
Button("Tap \(counter)") {
counter += 1
}
}
}
Use background modes in app capabilities (e.g., audio, location, fetch).
Use BackgroundTasks framework for deferred tasks in iOS 13+.
Perform heavy tasks in background threads using GCD or OperationQueue.
iOS apps use Apple Push Notification Service (APNs) to receive notifications.
Steps:
App registers for push notifications.
APNs sends device token.
Server sends payload to APNs with device token.
APNs delivers to device.
Can handle notifications foreground, background, and terminated states.
UserDefaults: Small key-value storage.
Core Data: Object graph and database.
Keychain: Secure data storage (passwords, tokens).
File System: Saving files in Documents or Caches.
Realm: Third-party database for faster object persistence.
@State, @Binding, @ObservedObject, and @EnvironmentObject in SwiftUI?| Property Wrapper | Purpose |
|---|---|
| @State | Local state of a view |
| @Binding | Two-way binding with another view’s state |
| @ObservedObject | Observes external class conforming to ObservableObject |
| @EnvironmentObject | Shared state across multiple views |
viewDidLoad, viewWillAppear, and viewDidAppearviewDidLoad: Called once when view is loaded. Initialize data/UI.
viewWillAppear: Called every time before view appears. Update UI or animations.
viewDidAppear: Called after view appears. Start animations or tracking.
Use MVVM + Coordinator pattern to separate navigation from business logic.
Use Dependency Injection for better testability.
Use Combine/RxSwift for reactive UI updates.
Modularize features to separate frameworks and maintain codebase.
Answer:
The Coordinator pattern is used to manage navigation and flow in an iOS app.
It separates navigation logic from ViewControllers, improving modularity and testability.
Each coordinator handles a feature or flow in the app.
Example:
class AppCoordinator {
var navigationController: UINavigationController
func start() {
let homeVC = HomeViewController()
homeVC.coordinator = self
navigationController.pushViewController(homeVC, animated: true)
}
func goToDetails() {
let detailsVC = DetailsViewController()
navigationController.pushViewController(detailsVC, animated: true)
}
}
OperationQueue and GCD?| Feature | OperationQueue | GCD (DispatchQueue) |
|---|---|---|
| Abstraction | High-level, object-oriented | Low-level C API |
| Dependencies | Supports dependencies between operations | No built-in dependencies |
| Cancellation | Can cancel operations | No built-in cancellation |
| Priorities | Supports priorities | QoS for queues |
Use Case: Use OperationQueue when you need dependencies, priorities, or cancellation. Use GCD for simple concurrent tasks.
Use weak references for delegates:
protocol Delegate: AnyObject {}
class MyClass {
weak var delegate: Delegate?
}
Use [weak self] or [unowned self] in closures.
Avoid strong reference cycles in view controller hierarchies.
Monitor leaks using Xcode Instruments → Leaks.
Lightweight Migration: Automatic migration if small schema changes (add/remove attributes).
Heavyweight Migration: Manual migration for complex changes using mapping models.
Always test migration paths to avoid app crashes when updating data models.
NSCache: In-memory cache for images or data, auto-purged under memory pressure.
URLCache: Cache network responses.
Disk Cache: Store large data on file system.
Third-party libraries: Kingfisher, SDWebImage for image caching.
Property wrappers add behavior to properties.
Common wrappers: @State, @Binding, @ObservedObject, @Published.
Custom example:
@propertyWrapper
struct Capitalized {
private var value: String = ""
var wrappedValue: String {
get { value }
set { value = newValue.capitalized }
}
}
struct User {
@Capitalized var name: String
}
@Published and @ObservedObject?@Published marks a property inside a class conforming to ObservableObject to trigger UI updates.
@ObservedObject is used in a SwiftUI view to observe changes in the object.
Reuse cells using dequeueReusableCell.
Avoid heavy layout calculations in cellForRow.
Use prefetching APIs for large datasets.
Cache images and async load them.
Avoid nested loops inside cell rendering.
background fetch and silent push notifications?| Feature | Background Fetch | Silent Push |
|---|---|---|
| Trigger | iOS decides when to run | Server triggers |
| Use | Fetch small data periodically | Update data in background |
| Limitations | No guaranteed execution time | Limited execution time |
| Requires | Background mode capability | Push notification entitlement |
Use URLSession(configuration: .background) for downloads/uploads that continue even when app is suspended or killed.
Requires delegate methods to handle completion, progress, and errors.
Example:
let config = URLSessionConfiguration.background(withIdentifier: "com.app.bg")
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
Use GCD for async tasks.
Use OperationQueue for dependencies and cancellations.
Always update UI on the main thread:
DispatchQueue.main.async {
self.tableView.reloadData()
}
Synchronous and Asynchronous Core Data operationsSynchronous: Main context performs operations on main thread (blocks UI).
Asynchronous: Use background context for heavy fetches or inserts to keep UI responsive.
weak, unowned, and strong in Swift with closuresStrong closure: Captures self strongly → retain cycle.
Weak closure: Optional self; avoids cycle, may be nil.
Unowned closure: Non-optional self; crashes if self deallocated.
Generics allow writing reusable and type-safe code.
Example:
func swapValues<T>(_ a: inout T, _ b: inout T) {
let temp = a
a = b
b = temp
}
Widely used in Collections, Network Responses, and Custom Data Structures.
Throwing functions: func readFile() throws -> String
Do-Catch:
do {
let result = try readFile()
} catch {
print(error.localizedDescription)
}
Result type:
func fetchData() -> Result<Data, Error> {}
Universal Links: Open specific content in the app using HTTP/HTTPS links.
Custom URL schemes: Open app with myapp://.
Update AppDelegate or SceneDelegate to handle URLs.
UIApplicationDelegate and SceneDelegate?UIApplicationDelegate: Handles app-level events (launch, background, push notifications).
SceneDelegate: Introduced in iOS 13 to handle multiple UI scenes (multi-window support on iPad).
UIKit and SwiftUI| Feature | UIKit | SwiftUI |
|---|---|---|
| Paradigm | Imperative | Declarative |
| UI Updates | Manual | Automatic with state binding |
| Preview | Only runtime | Live previews in Xcode |
| Learning curve | Established, extensive | Newer, simpler syntax |
| Interoperability | Easy to use Objective-C | Can embed UIKit using UIViewRepresentable |
Use XCTest framework.
Test business logic, models, and network responses.
Use mocking for API calls or dependencies.
Use XCUITest for UI automation testing.
Instruments: CPU, Memory, Time Profiler, Leaks, Network.
Xcode Debug Navigator: Check memory usage, CPU, and disk.
Optimize:
Lazy loading
Efficient layouts
Background processing
lazy var and computed properties in Swift| Feature | Lazy Variable | Computed Property |
|---|---|---|
| Initialization | Initialized once when first accessed | Calculated every time accessed |
| Storage | Stores value in memory | No storage; calculated on access |
| Use Case | Heavy objects, deferred initialization | Derived values, dynamic calculations |
| Mutability | Can be modified if declared var | Read-only or read-write depending on getter/setter |
Example:
lazy var heavyObject = HeavyClass()
var computedValue: Int { return array.count * 2 }
Answer:
Codable is a protocol used to encode and decode data for JSON, plist, or other formats.
Combines Encodable and Decodable protocols.
Simplifies parsing APIs without writing boilerplate code.
Example:
struct User: Codable {
var name: String
var age: Int
}
let jsonData = try JSONEncoder().encode(user)
let decodedUser = try JSONDecoder().decode(User.self, from: jsonData)
NSManagedObjectContext types in Core Data| Context Type | Description |
|---|---|
| Main Context | Runs on main thread; use for UI updates |
| Background Context | Runs on background thread; use for heavy fetches/inserts |
| Private Context | Fully isolated; can merge changes with main context |
Tip: Always save background contexts asynchronously to avoid blocking UI.
weak, unowned, and strong in SwiftStrong: Keeps reference; default.
Weak: Optional, avoids retain cycles; auto nil when object deallocates.
Unowned: Non-optional; assumes object always exists; crashes if object is nil.
Example in closures:
closure = { [weak self] in self?.doSomething() }
closure = { [unowned self] in doSomething() }
Background Modes: Enable capabilities (audio, location, fetch).
BackgroundTasks framework (iOS 13+): Schedule tasks for deferred execution.
GCD/OperationQueue: Perform heavy tasks in background threads.
Example:
let task = BGAppRefreshTaskRequest(identifier: "com.app.refresh")
task.earliestBeginDate = Date(timeIntervalSinceNow: 15 * 60)
try BGTaskScheduler.shared.submit(task)
UIView Animations: Basic animations for properties.
UIView.animate(withDuration: 0.5) {
view.alpha = 0.5
}
Core Animation (CALayer): More control, keyframe and path animations.
SwiftUI Animations: Declarative animations using .animation() and .withAnimation().
Lottie Animations: Third-party library for JSON-based animations.
DispatchGroup in GCDUsed to wait for multiple asynchronous tasks to complete.
Example:
let group = DispatchGroup()
group.enter()
asyncTask1 { group.leave() }
group.enter()
asyncTask2 { group.leave() }
group.notify(queue: .main) {
print("All tasks completed")
}
Defer heavy work to background threads.
Lazy-load non-essential resources.
Use Static TableViews or SwiftUI Views for initial screen.
Preload assets asynchronously.
Profile using Time Profiler in Instruments.
viewDidLoad, viewWillAppear, viewDidAppear, viewWillDisappear, and viewDidDisappear?| Method | When called | Use Case |
|---|---|---|
| viewDidLoad | Once when view is loaded | Setup UI, initial data |
| viewWillAppear | Every time view is about to appear | Update UI, start animations |
| viewDidAppear | After view appears | Start timers, tracking |
| viewWillDisappear | Before view disappears | Save data, cancel tasks |
| viewDidDisappear | After view disappears | Release resources |
Push Notifications: Notify user via APNs.
Silent Notifications: Trigger background updates without alerting the user.
Use Cases: Sync data, refresh content, background fetch.
Implementation: Handle in didReceiveRemoteNotification and configure content-available: 1 in payload.
| Feature | Synchronous | Asynchronous |
|---|---|---|
| Thread Blocking | Blocks current thread | Runs in background |
| UI Impact | Freezes UI | UI responsive |
| Usage | Rare | Recommended (URLSession) |
Example with URLSession:
URLSession.shared.dataTask(with: url) { data, _, error in
// Handle data asynchronously
}.resume()
Use Codable for type-safe decoding/encoding.
Use JSONDecoder().keyDecodingStrategy to handle snake_case vs camelCase.
For large datasets, parse in background thread to avoid blocking UI.
Example:
DispatchQueue.global().async {
let user = try? JSONDecoder().decode(User.self, from: data)
DispatchQueue.main.async {
self.updateUI(user)
}
}
Framework for reactive programming.
Handles asynchronous data streams and event-driven UI updates.
Key concepts: Publisher, Subscriber, Subject, Operators.
Example:
let publisher = [1, 2, 3].publisher
let subscriber = publisher.sink { value in
print(value)
}
Combine is often used with MVVM to bind ViewModel to View.
Continue downloads/uploads even when app is suspended or terminated.
Must implement delegate methods to handle completion and progress.
let config = URLSessionConfiguration.background(withIdentifier: "com.app.bg")
let session = URLSession(configuration: config, delegate: self, delegateQueue: nil)
Use Keychain for storing passwords and tokens.
Avoid storing sensitive data in UserDefaults.
Use HTTPS/SSL pinning for network requests.
Enable App Transport Security (ATS).
Obfuscate code if necessary to prevent reverse engineering.