Swift and SwiftUI tutorials for Swift Developers

Over 200 SwiftUI iOS Interview Questions

If you are preparing for an iOS or macOS developer interview today, SwiftUI is no longer optional; it is the standard. Companies no longer just ask “do you know how to use it?”, but rather “do you understand how its state management and rendering engine work?”.

To help you master the technical interview, I have compiled a massive collection of questions. In this first part of our series, we cover the 200 essential questions in a “Lightning Round” format: direct questions with concise answers to refresh your memory quickly.


🟢 Level 1: Fundamental Concepts

These questions verify if you understand the philosophy behind the framework.

  1. What is SwiftUI? It is a declarative user interface framework created by Apple to build UIs across all its platforms (iOS, macOS, watchOS, tvOS) using Swift.
  2. What is the main difference between SwiftUI and UIKit? SwiftUI is declarative (you describe what you want the UI to do), while UIKit is imperative (you describe how to build and modify it step-by-step).
  3. What does it mean that SwiftUI is “Declarative”? It means the code defines the final state of the interface, and the system handles rendering the changes when the state varies, rather than managing transitions manually.
  4. Why are Views in SwiftUI Structs and not Classes? Structs are value types, lighter, and faster to create. This allows SwiftUI to recreate them thousands of times without performance impact, facilitating the “diffing” system used to update the screen.
  5. What is the View protocol? It is the base protocol of SwiftUI. Anything drawn on the screen must conform to Viewand define a body property.
  6. What type does the body property return? It returns some View.
  7. What does some View (Opaque Return Type) mean? It indicates that the property returns something that conforms to the View protocol, but hides the concrete type (which could be very complex, like VStack<TupleView<...>>) from the external compiler.
  8. What is a Modifier? It is a method that creates a new view by applying a change to the original view (e.g., .padding().background()).
  9. Does the order of modifiers matter? Yes, absolutely. .background(Color.red).padding() is different from .padding().background(Color.red).
  10. What is the Canvas in Xcode? It is the interactive preview area that shows SwiftUI code changes in real-time without needing to compile the entire app.
  11. What is PreviewProvider (or the #Preview macro)? It is the code that generates the preview in the Canvas. Since Xcode 15, the #Preview macro is used to simplify the syntax.
  12. Does SwiftUI support Auto Layout? Not directly. SwiftUI uses its own layout system based on Stacks, Spacers, and Alignment, although underneath it uses technologies similar to the layout engine.
  13. How do you debug a view in SwiftUI? You can use Self._printChanges() inside the view body to see what caused the redraw, or use Xcode’s View Debuggers.
  14. What is the basic lifecycle of a view? Initialization -> onAppear -> Updates (due to state changes) -> onDisappear.
  15. What is a Group? A container that groups views without applying any visual layout (it doesn’t stack them), useful for overcoming the 10-view limit per container or applying modifiers to multiple views at once.

🔵 Level 2: State Management (The Core of SwiftUI)

If you fail here, you fail the interview. Understanding data flow is vital.

  1. What is the “Source of Truth”? The concept that data should exist in a single place, and views should only read or react to that data, not duplicate it.
  2. What does @State do? It declares a mutable property owned by the view. When it changes, SwiftUI automatically redraws the view. It is used for simple local states (e.g., a toggle).
  3. Why must @State be declared as private? Because it is designed to be used only internally by the view that creates it.
  4. What is @Binding? It allows a child view to read and write a value owned by a parent view without owning the data itself. It is a read/write reference.
  5. What is the difference between @ObservedObject and @StateObject? @StateObject ensures the object is created only once and persists even if the view redraws. @ObservedObject does not guarantee persistence if the owning view is destroyed and recreated; it is used for injected objects that already exist.
  6. When would you use @EnvironmentObject? For data that needs to be accessed by many views in the hierarchy (like a user profile or theme settings) without having to pass them manually from parent to child (prop drilling).
  7. What protocol must a class conform to in order to use @Published? ObservableObject.
  8. What does the @Published property do? It automatically notifies observers when the variable’s value changes, triggering UI updates.
  9. What is @Environment? It allows reading values from the system environment, such as dark mode (.colorScheme), horizontal size class, or locale settings.
  10. What is @AppStorage? A property wrapper that connects a variable directly to UserDefaults. If the value in UserDefaults changes, the view updates.
  11. What is @SceneStorage? Similar to @AppStorage but for persisting the state of a specific scene (useful for state restoration in iPad multitasking).
  12. What is Binding.constant(value)? It creates an immutable binding, useful primarily for Previews where you need to pass a binding but don’t need real logic.
  13. How do you communicate changes from a child view to a parent without Bindings? You can use Closures(callbacks) or PreferenceKeys.
  14. What are PreferenceKeys? An advanced mechanism to pass data up the hierarchy (from child to parent), opposite to the normal data flow.
  15. Is it good practice to use Singletons in SwiftUI? Generally not for dependency injection into views. It is better to use @EnvironmentObject or injection in the initializer to facilitate testing.

🟠 Level 3: Layout and Design

  1. What are the three main stacks? VStack (Vertical), HStack (Horizontal), ZStack (Depth/Overlay).
  2. What does a Spacer do? It occupies all available space on the axis of its containing stack, pushing the rest of the content.
  3. How does Frame work? It modifies the size proposed to the view. .frame(maxWidth: .infinity) makes the view take up all possible width.
  4. What is GeometryReader? A container that gives you access to the size and coordinates of its parent view. Useful for complex responsive designs.
  5. What is the main problem with using GeometryReader everywhere? It can break SwiftUI’s natural automatic layout and is performance-heavy if abused; it often tends to take up all available space.
  6. What are LazyVStack and LazyHStack? Stacks that only render views that are currently visible on the screen. Essential for long scrolling lists to improve performance.
  7. How do you create a Grid? Using LazyVGrid or LazyHGrid along with GridItem.
  8. What is the SafeArea? The areas of the screen obstructed by system elements (the notch, the Dynamic Island, the home bar).
  9. How do you ignore the Safe Area? Using the .ignoresSafeArea() modifier.
  10. How do you prioritize which view shrinks if there is no space? Using .layoutPriority(Double). Views with higher priority keep their size; those with lower priority shrink or truncate.
  11. What is the .overlay() modifier? Places a view on top of another (in front of the user), similar to a ZStack but coupled to the size of the original view.
  12. What is the .background() modifier? Places a view behind another.
  13. How do you round the corners of a view? .cornerRadius() (deprecated) or .clipShape(RoundedRectangle(...)).
  14. How do you apply shadows? With the .shadow() modifier.
  15. What is ImageScale? It defines the relative size of SF Symbols (small, medium, large) independently of their font size.

🟣 Level 4: Lists and Navigation

  1. What is the difference between List and ForEach inside a ScrollView? List has a native system appearance (UIKit table style) and built-in loading optimizations (lazy). ScrollView + ForEach is fully customizable but does not recycle cells automatically unless you use LazyVStack.
  2. What protocol must elements of a List conform to? Identifiable, or you must provide an explicit id: \.self.
  3. What is the purpose of the id property in Identifiable? So SwiftUI knows how to distinguish which row is which, especially when animating changes, insertions, or deletions.
  4. How do you handle navigation in iOS 16+? With NavigationStack and navigationDestination(for:).
  5. Why was NavigationView deprecated? It had inconsistent behaviors between iPhone and iPad (split view) and handling programmatic navigation (deep linking) was difficult.
  6. How do you perform programmatic navigation (go to a screen via code)? Using a NavigationPath or a binding to an array of data inside NavigationStack.
  7. What is NavigationLink? The button or area that triggers the transition to a new view within a navigation stack.
  8. How do you show a modal window (Sheet)? Using the .sheet(isPresented: content:) or .sheet(item: content:) modifier.
  9. Difference between .sheet and .fullScreenCover? .sheet shows the card-style view (part of the previous view is seen behind), .fullScreenCover occupies the entire screen.
  10. What is TabView? The equivalent of UITabBarController, allows navigation via bottom tabs (or side tabs on iPad/macOS).
  11. How do you create a paginated image carousel? Using TabView with the .tabViewStyle(.page) style.
  12. How do you add a title to the navigation bar? With the .navigationTitle("Title") modifier applied to the view insidethe stack.
  13. How do you add buttons to the navigation bar? With .toolbar { ... } and ToolbarItem.
  14. How do you show an alert? With the .alert() modifier, bound to a boolean state or an optional error object.
  15. How do you implement “Pull to Refresh”? Adding the .refreshable { ... } modifier to a List or ScrollView.

🔴 Level 5: Interoperability and Advanced

  1. How do you use a UIKit view in SwiftUI? Creating a struct that conforms to UIViewRepresentable.
  2. What methods must you implement in UIViewRepresentable? makeUIView(context:) and updateUIView(_:context:).
  3. What is the Coordinator in UIViewRepresentable? It acts as the bridge to receive events from UIKit (like delegates or targets) and communicate them back to SwiftUI.
  4. How do you use a UIViewController in SwiftUI? Using UIViewControllerRepresentable.
  5. How do you use a SwiftUI view in a UIKit project? Wrapping it in a UIHostingController.
  6. What is AnyLayout (iOS 16)? A type that allows dynamically switching between layout types (e.g., from VStack to HStack) while maintaining the identity of views for fluid animations.
  7. How do you manage explicit animations? Wrapping the state change in a withAnimation { ... } block.
  8. What are implicit animations? The .animation(.default, value: variable) modifier that automatically animates when variable changes.
  9. What does matchedGeometryEffect do? It allows animating the movement of a view from one position/hierarchy to a different one, creating fluid “Hero animation” transitions.
  10. What is TimelineView? A view that updates periodically according to a schedule, useful for clocks or complex time-based animations.
  11. What is Canvas (the view, not the preview)? A view for high-performance 2D drawing (similar to drawRect in CoreGraphics) using an immediate mode drawing context.
  12. How do you handle asynchronous tasks when a view appears? Using the .task modifier. It is better than onAppearbecause it automatically cancels the task if the view disappears before finishing.
  13. What is AsyncImage? A native view for downloading and displaying images from a URL.
  14. What is the limitation of AsyncImage? It does not have built-in disk caching by default (only temporary memory while the view lives). For real caching, external libraries or custom implementations are usually used.
  15. What is ViewBuilder? A function attribute (result builder) that allows constructing views from closure blocks, enabling DSL-like syntax (like inside a VStack).
  16. Can you create your own containers like VStack? Yes, using the Layout protocol (iOS 16+).
  17. What is FocusState? A property wrapper to control keyboard focus on text fields (making the keyboard appear or disappear programmatically).
  18. How do you support Dark Mode in custom colors? Defining the color in the Asset Catalog with “Any” and “Dark” variants, or using semantic system colors (.systemBackground).
  19. What is Dynamic Type? The app’s ability to scale font size according to the user’s settings. SwiftUI supports this by default.
  20. How do you limit the number of lines in a text? .lineLimit(n).

⚫ Level 6: Architecture and Data (Core Data / SwiftData)

  1. Is MVVM the only architecture for SwiftUI? No. Although it is the most common, patterns like “The Composable Architecture” (TCA) or Redux are also popular due to the declarative nature of SwiftUI.
  2. What is the role of the ViewModel in SwiftUI? Transforming model data into state ready for the view and handling business logic (user actions).
  3. What property wrapper is used to inject a Core Data context? @Environment(\.managedObjectContext).
  4. How do you fetch Core Data in a view? Using @FetchRequest.
  5. What is SwiftData? The modern successor to Core Data, designed purely for Swift and SwiftUI, released in iOS 17.
  6. How do you define a model in SwiftData? Using the @Model macro before the class.
  7. How do you query data in SwiftData inside a view? Using the @Query macro.
  8. What problem do very large views in a single file have? The compiler takes longer to infer types, the preview is slow, and the code is hard to read. Extracting subviews is recommended.
  9. What is the difference between a computed property (var body: some View) and a subview struct? The structis better for performance because SwiftUI can cache it and optimize its redrawing independently. The computed property is always re-evaluated when the parent body changes.
  10. How do you test a SwiftUI view? It is difficult to Unit Test views. Using UI Tests (XCUITest) or using the library ViewInspector to inspect the hierarchy in unit tests is recommended.
  11. What is the .redacted(reason: .placeholder) modifier? It converts the view content into gray blocks, ideal for automatic loading states (skeletons).
  12. How do you handle global errors? Often by injecting an error manager into the Environment or using a global state that triggers alerts in the root view.
  13. What is MainActor? An attribute that ensures code runs on the main thread. ViewModels (ObservableObject) are usually marked with @MainActor to ensure UI updates happen on the correct thread.
  14. How do you optimize a list that lags when scrolling?
    1. Use Identifiable correctly. 2. Reduce the complexity of each row. 3. Ensure images load asynchronously. 4. Avoid heavy calculations in the body.
  15. What is EquatableView used for? It allows defining custom rules to decide if a view needs to be redrawn by comparing its old and new state, avoiding unnecessary renders.

⚪ Level 7: macOS and Multiplatform

  1. Does SwiftUI work the same on macOS as on iOS? 90% yes, but macOS has different paradigms (multiple windows, menu bar, mouse vs. touch events).
  2. What is Settings in the App structure? It defines the preferences/settings window on macOS (Command + ,).
  3. How do you detect if you are on macOS or iOS at compile time? Using #if os(macOS) … #endif.
  4. How do you handle Mouse Hover on macOS/iPadOS? Using the .onHover { isHovering in ... } modifier.
  5. What is Commands in the App structure? It allows modifying the system menu bar (File, Edit, etc. menus) on macOS.

♿ Level 8: Accessibility (The Key Differentiator)

Big companies (and Apple) value this enormously. If you ignore this section, you are ignoring millions of users.

  1. How do you make a decorative image ignored by VoiceOver? Using the .accessibilityHidden(true) modifier.
  2. What is the difference between .accessibilityLabel and .accessibilityValue? The Label describes what the element is (e.g., “Volume”), and the Value describes its current state (e.g., “50%”).
  3. What is .accessibilityHint? An optional instruction explaining what will happen if the user interacts with the element (e.g., “Double tap to mute”).
  4. How do you group multiple text elements so VoiceOver reads them as a single sentence? Using the .accessibilityElement(children: .combine) modifier.
  5. What is Sort Priority in accessibility? It defines the order in which VoiceOver reads elements. It is controlled with .accessibilitySortPriority(Double).
  6. How do you support Dynamic Type in complex layouts that might break? Using ViewThatFits or detecting the sizeCategory in the environment to switch from HStack to VStack if the font is too large.
  7. What is .accessibilityAddTraits? It adds characteristics to the element, such as .isButton or .isHeader, so the screen reader knows how to treat it.
  8. How do you test accessibility without a physical device? Using the “Accessibility Inspector” tool in Xcode.
  9. How do you make a custom button behave like a native button for VoiceOver? Ensuring it has the .isButton trait and does not hide its action.
  10. What is “Reduce Motion” and how do you respect it in SwiftUI? It is a user preference to minimize motion sickness. It is read from @Environment(\.accessibilityReduceMotion) and you should use it to disable or simplify animations.

🎨 Level 9: Advanced Graphics, Animations, and Layouts

  1. What is the Animatable protocol? It allows animating changes in properties that are not animatable by default (like vertices of a custom shape) by defining animatableData.
  2. What is AnimatablePair? A type that allows animating two values simultaneously within animatableData (e.g., X and Y coordinates).
  3. What is the difference between .transition and .animation? .animation smooths the change of properties of an existing view (color, size). .transition defines how a view enters or leaves the hierarchy (fade in, slide out).
  4. Why might a transition not work? Usually because the view is not actually being removed/inserted into the tree (e.g., using opacity instead of a conditional if).
  5. What is Canvas in terms of graphics (SwiftUI 3.0+)? A view providing a high-performance immediate mode graphics context (similar to drawRect in Core Graphics), ideal for particles or complex drawing.
  6. What is TimelineView and what is it used for in animations? It allows redrawing a view periodically (even frame-by-frame), useful for time-based animations or physics that don’t depend on state changes.
  7. How do you create a Custom Shape? By creating a struct that conforms to Shape and implementing path(in rect: CGRect).
  8. What is a Shader in SwiftUI (iOS 17+)? It allows applying visual effects written in Metal (MSL) directly to views using modifiers like .colorEffect or .distortionEffect.
  9. What is the .drawingGroup() modifier? It flattens the view hierarchy into a single image rendered by Metal. It is used to solve performance issues in complex lists or heavy graphics.
  10. What is Anchor<T>? An opaque type that stores geometric information of a view to be used by another view in the hierarchy (usually with preferences).
  11. How does matchedGeometryEffect work if you have two views with the same ID on screen? It is undefined behavior and will cause visual glitches. IDs must be unique per active animation group.
  12. What is the Layout protocol (iOS 16)? It allows creating custom containers (like your own Grid or Flow Layout) by defining how to measure and place subviews.
  13. Difference between Path and Shape? Shape is a View that adjusts to a space. Path is the mathematical description of a line/curve that can be used inside a Shape.
  14. How do you apply a gradient to text? Using .foregroundStyle(Gradient...) (iOS 15+).
  15. What is VisualEffectView in SwiftUI? It doesn’t exist directly; Material is used (e.g., .background(.ultraThinMaterial)).

⚡ Level 10: Concurrency and Lifecycle (Swift 5.5+)

  1. Why use .task instead of .onAppear? .task supports async/await natively and is automatically canceled if the view is destroyed before the task finishes.
  2. What does @MainActor mean in a ViewModel? It guarantees that all properties and methods of that class are accessed/executed on the main thread, preventing UI update errors from background threads.
  3. What happens if you modify a @Published property from a background thread? SwiftUI will throw a runtime warning (purple warning) and it could cause crashes or strange UI behavior.
  4. What is Sendable and how does it affect SwiftUI? It is a protocol indicating that it is safe to pass data between threads. Data passed to views (especially in .task closures) should be Sendable.
  5. How do you handle a Data Race in SwiftUI? Using actors (actor), isolation with @MainActor, and avoiding unprotected mutable shared state.
  6. Does the body of a view execute on the Main Thread? Yes, always.
  7. How do you stop an ongoing task when the user navigates back? If you use .task, it’s automatic. If you use a manual Task { } in onAppear, you must save the reference and call .cancel() in onDisappear.
  8. What is AsyncSequence in the context of SwiftUI? It allows iterating over asynchronous data streams (like notifications or download bytes) updating the UI step-by-step.
  9. Can you use await inside a button? Not directly in the button’s closure. You must wrap the call in Task { await ... }.
  10. What is ViewInspector? It is not native, but it is the de facto standard open-source library for performing Unit Tests on the SwiftUI view hierarchy.

📱 Level 11: Ecosystem (Widgets, WatchOS, Live Activities)

  1. Which framework is used to create Home Screen Widgets? WidgetKit, which uses SwiftUI exclusively.
  2. What is a TimelineEntry in WidgetKit? An object representing the state of the widget at a specific point in time.
  3. Why are animations limited in Widgets? Because widgets are serialized “snapshots”, not live views running constantly (although iOS 17 improved this).
  4. What is a Live Activity? An interactive and persistent notification on the Lock Screen (and Dynamic Island) for real-time events (e.g., food delivery).
  5. What is DynamicIsland? The SwiftUI API to define how your Live Activity looks on the “island” of the iPhone 14 Pro/15.
  6. In watchOS, what replaces NavigationView or NavigationStack for the base hierarchy? Generally NavigationStack is used as well, but the pagination style (.tabViewStyle(.verticalPage)) is very common.
  7. What is .digitalCrownRotation? A watchOS-exclusive modifier to read the value of the digital crown.
  8. How do you share UI code between an iOS App and a Widget? Extracting views to a local package (Swift Package) or including them in both Targets.
  9. What are App Clips? A small part of your app (under 10-15MB) that runs instantly without full installation. Built with SwiftUI.
  10. What is WidgetURL? A modifier that defines which URL opens in the main app when the user taps the widget.

🧩 Level 12: Advanced Data Architecture

  1. What is Preference in SwiftUI? A communication channel from children to parents. Children send data, the parent collects and reduces it.
  2. What is AnchorPreference? It allows passing bounds and coordinates from a child view to a parent (useful for tooltips or guided highlights).
  3. How do you inject dependencies into a custom Environment? Creating a custom EnvironmentKey and extending EnvironmentValues.
  4. What problem does AnyView solve and why should you avoid it? It allows type erasure of a view to return different types in an if/else. It should be avoided because it destroys SwiftUI’s “diffing” optimization, reducing performance.
  5. Instead of AnyView, what should you use? @ViewBuilder or Group.
  6. What is the “Coordinator” pattern in SwiftUI? An external class responsible for navigation logic, separating the view from the decision of “where to go”.
  7. Is it possible to use Redux in SwiftUI? Yes, it is very compatible. You usually have a global Store as an ObservableObject and pure Reducers.
  8. What is the difference between @StateObject and a static global variable? @StateObject is tied to the view’s lifecycle (released if the view dies). The global variable lives forever (potential memory leak).
  9. How do you force a view update manually (though not recommended)? Using objectWillChange.send() on an ObservableObject.
  10. How do you detect when the app goes to the background? Using .onChange(of: scenePhase).

🛠 Level 13: Debugging and Performance (Troubleshooting)

  1. Why is my view constantly redrawing (infinite loop)? You are probably modifying a @State inside the body or in a constructor, which triggers a new render, which modifies the state again.
  2. How do you identify which view is causing slowness? Using “SwiftUI View Hierarchy” in Instruments or the “Color Blended Layers” option in the simulator.
  3. Why does List perform poorly with thousands of complex items? Sometimes List does not recycle cells as efficiently as UICollectionView. It is suggested to simplify the cell or use LazyVStack inside a ScrollView if List fails.
  4. What does the error “Modifying state during view update, this will cause undefined behavior” mean? That you are changing data while SwiftUI is calculating the layout (e.g., inside a GeometryReader updating a parent @Statedirectly).
  5. How do you fix the error above? Wrapping the state change in DispatchQueue.main.async or using .onAppear / .task.
  6. What impact does using .shadow() have on performance? High. Shadows require off-screen rendering. Better to use pre-rendered images or simulated shadows if possible.
  7. What is the “Opaque Return Type” and how does it affect compilation? (some View). It helps the compiler work faster by not having to infer the entire chain of nested generic types.
  8. Why does my @Published not update the view? Maybe the view is not observing the object with @ObservedObject or @StateObject, or the update happens in a nested property of a class (classes are reference types and @Published does not observe deep changes automatically).

🧪 Level 14: Swift Charts, MapKit, and New APIs

  1. How do you create a simple bar chart? Using the Charts framework and the Chart { BarMark(...) } view.
  2. What is Plottable? The protocol that data must conform to in order to be represented in Swift Charts (Strings, Ints, Dates, etc.).
  3. How do you show the native map in SwiftUI (iOS 17)? Using the Map() view. It no longer requires mandatory region binding in newer versions.
  4. What is MapAnnotation vs Marker? Marker is the standard pin (balloon) with better performance. MapAnnotation allows using a fully custom SwiftUI view as a pin.
  5. What is ShareLink? The native view to present the system Share Sheet.
  6. How do you implement “Search” in a list? Using the .searchable(text: $text) modifier.
  7. What is contentTransition? Defines how the content of a view changes (e.g., numbers spinning like a counter) using .contentTransition(.numericText()).

🔥 Level 15: Trick Questions / Code Scenarios

The interviewer shows you code and asks: “What happens here?”

  1. Scenario: You have a VStack with Spacing: 0 and two rectangles of height 50. Is the total height 100? Answer: Not necessarily. The Safe Area or the parent container could compress them if there is no space.
  2. Scenario: You use @State for a class object (class User). Does it work? Answer: It works, but the view will not update when properties inside User change, because @State only observes the change of the class pointer, not its contents.
  3. Scenario: You have a NavigationLink inside a List but it doesn’t work when tapped. Answer: Often happens if you have a Button inside the row that captures the touch, or if you forgot the parent NavigationStack.
  4. Scenario: Text("Hello").padding().background(Color.red).padding() vs Text("Hello").padding().padding().background(Color.red).Answer: In the first one, red surrounds the text with one margin. In the second, red surrounds the text with double margin (the red block looks bigger, or further from the text depending on visual interpretation). Order matters.
  5. Scenario: Why does a LazyVGrid inside a horizontal ScrollView look bad? Answer: Because LazyVGrid grows vertically. You should use LazyHGrid inside a horizontal Scroll.
  6. Scenario: You try to apply .frame to an image, but it doesn’t resize. Answer: You forgot .resizable() before the frame.
  7. Scenario: Can a @Binding be optional (Binding<Bool?>)? Answer: Yes, it is possible.
  8. Scenario: What happens if you call an impure function in bodyAnswer: It will execute multiple times unpredictably, causing side effects (bugs).
  9. Scenario: How do you hide the navigation bar? Answer: .toolbar(.hidden) or .navigationBarHidden(true) (deprecated).
  10. Scenario: You have a ForEach with a range 0..<items.count. Is it safe? Answer: It is dangerous. If the array changes size, it will cause an “Index out of range” crash. Always use ForEach(items) with Identifiable.

🏆 Level 16: The Master Touch (Miscellaneous)

  1. What is FocusState? Controls which text field has keyboard focus.
  2. What is SubmitLabel? Changes the keyboard “Enter” button (e.g., to “Search”, “Go”, “Next”).
  3. How do you detect screenshots? Listening for the userDidTakeScreenshotNotification in onReceive.
  4. How do you add a context menu (long press)? With the .contextMenu modifier.
  5. What is Menu in SwiftUI? A button that displays a list of options when tapped (does not require long press).
  6. How do you use custom fonts? Adding the file to Info.plist and using .font(.custom("Name", size: 12)).
  7. What is Label? A view that combines an icon and text automatically aligned.
  8. How do you force Light Mode on a specific view? .preferredColorScheme(.light).
  9. What is Stepper? A control to increment/decrement a numeric value.
  10. What is DisclosureGroup? A collapsible view (accordion) that shows or hides content.
  11. How do you do “Swipe Actions” in a list? Using the .swipeActions modifier on the cell.
  12. What is OutlineGroup? To show hierarchical data structures (trees) in an expandable list.
  13. How do you align text to the left in a VStack? VStack(alignment: .leading).
  14. Why doesn’t Spacer() work in a ZStack? Because ZStack overlays elements, it doesn’t distribute them along an axis.
  15. What is EmptyView? A view that occupies no space and renders nothing. Useful as a default return in @ViewBuilder.
  16. What is Divider? A thin visual line (horizontal or vertical depending on the stack) to separate content.
  17. How do you detect device orientation? Using GeometryReader and comparing width vs height, or listening to changes in UIDevice.
  18. What is ScaledMetric? A property wrapper that scales a numeric value (like an icon size) proportionally to the user’s text size settings.
  19. Can you use CoreData without NSPersistentCloudKitContainer in SwiftUI? Yes, but you lose automatic iCloud synchronization.
  20. If you had to define SwiftUI in one sentence to convince a manager, what would you say? “SwiftUI reduces UI code by 60%, eliminates entire categories of state bugs, and drastically speeds up design iteration thanks to its declarative nature and real-time previews.”
Leave a Reply

Your email address will not be published. Required fields are marked *

Previous Article

How to show a Mac toolbar in SwiftUI

Next Article

Over 165 Swift iOS Interview Questions

Related Posts