iOS Interview Questions (SwiftUI)

Updated Mar 16, 2023#ios#swift#swiftui#interview

The existence of SwiftUI has somehow rendered UIKit obsolete, you should get busy learning SwiftUI because it is the future of app development on Apple platforms. Preparing for a SwiftUI interview involves a combination of learning the fundamental concepts of SwiftUI and practicing building user interfaces with the framework.



The Apple documentation provides a comprehensive overview of SwiftUI and its various components. Be sure to read through the documentation thoroughly and take notes on important concepts and features.

Since SwiftUI is built on top of Swift, it’s important to have a solid understanding of the Swift programming language. Be sure to review topics such as variables, functions, closures, classes, and structs.

If you’ve built any projects with SwiftUI in the past, be prepared to discuss them in detail during the interview. Be ready to explain the challenges you faced, how you overcame them, and what you learned in the process.

  1. Will SwiftUI replace UIKit?

SwiftUI was announced at WWDC 19 as a declarative framework to declare user interface for any Apple platform. You can integrate SwiftUI views with objects from the UIKit, AppKit, and WatchKit frameworks to take further advantage of platform-specific functionality.

@available(iOS 13, macOS 10.15, *)
struct MyView: View {
  var body: some View {
    Text("Hello, World!")
  }
}

SwiftUI is absolutely going to be the future of development for Apple’s platforms, but it will take a long time to gain adoption at the level of UIKit. As each year goes by, SwiftUI grows in strength, adoption, and support, and as SwiftUI grows UIKit will start to shrink.

  1. What is declarative UI programming?

Declarative UI programming patterns have become incredibly popular over the last few years. On the web with frameworks like React and Vue.js, in cross-platform development environments like React Native and Flutter, and through native tools like RxSwift and RxCocoa.

One key aspect of most declarative UI frameworks is that they aim to boil any kind of UI down into a series of components — which can then be combined and composed in order to form different sets of views, animations, and interactions.

  1. Difference between @StateObject and @ObservedObject?
class DataModel: ObservableObject {
  /* ... */
}

struct FooView: View {
  @StateObject private var model = DataModel()
  var body: some View {
    VStack {
      BarView(model: model)
    }
  }
}

struct BarView: View {
  @ObservedObject var model: DataModel
  var body: some View {
    Text("Hello")
  }
}

A property marked as @StateObject will keep its initially assigned ObservableObject instance as long as the view is needed, even when the struct gets recreated by SwiftUI.

An @ObservedObject is used to wrap ObservableObject instances that are not created or owned by the view that’s used in. Internally, SwiftUI will not keep an @ObservedObject around when it discards and recreates a view if this is needed for a fresh render.

  1. What are the benefits of using SwiftUI?
  • SwiftUI offers a unified UI framework for building user interfaces on all types of Apple devices.
  • SwiftUI has a declarative syntax which easy to use and learn.
  • SwiftUI has very simple, modern and clean syntax.
  • SwiftUI promotes reactive programming through Binding, State and the Combine.
  • SwiftUI provides a live preview using the canvas, an interactive interface editor.
  • SwiftUI integrates well with both UIKit and AppKit, it enables us to incrementally migrate existing projects.
  1. Why does SwiftUI use structs for views?

Swift provides a number of features that make structs better than classes in performance and thread-safety.

Structs are preferable if they are relatively small and copiable because copying is way safer than having multiple references to the same instance as happens with classes.

With Structs, there is much less need to worry about memory leaks or multiple threads racing to access/modify a single instance of a variable. This is especially important when passing around a variable to many classes and/or in a multithreaded environment. If you can always send a copy of your variable to other places, you never have to worry about that other place changing the value of your variable underneath you.

  1. How does an observable object announce changes?

ObservableObject is a type of object with a publisher that emits before the object has changed. By default an ObservableObject synthesizes an objectWillChange publisher that emits the changed value before any of its @Published properties changes.

Using @Published is the easiest way to control state updates, you can also call objectWillChange.send() manually to put out the news that our data has changed so that any subscribed views can refresh.

class Model: ObservableObject {
  @Published var name: String

  var age: Int {
    willSet {
      objectWillChange.send()
    }
  }

  init(name: String, age: Int) {
      self.name = name
      self.age = age
  }
}
  1. Why always declare state as private?

SwiftUI manages the storage of a property that you declare as state. When the value changes, SwiftUI updates the parts of the view hierarchy that depend on the value. Use state as the single source of truth for a given value stored in a view hierarchy.

struct PlayButton: View {
  @State private var isPlaying: Bool = false

  var body: some View {
    Button(isPlaying ? "Pause" : "Play") {
      isPlaying.toggle()
    }
  }
}

Don’t initialize a state property of a view at the point in the view hierarchy where you instantiate the view, because this can conflict with the storage management that SwiftUI provides.

To avoid this, always declare state as private, and place it in the highest view in the view hierarchy that needs access to the value. Then share the state with any child views that also need access, either directly for read-only access, or as a binding for read-write access.

  1. Does the order of SwiftUI modifiers matter?

When a modifier just changes the environment that its target view will be rendered in, then the order often doesn’t matter.

However, if that modifier can only be applied to a specific type of view, then we can only apply it as long as we’re dealing with that kind of view directly.

The order of modifiers that wrap their target view, on the other hand, often matters quite a lot, and a different modifier order can end up yielding a very different result.

  1. What is SwiftUI, and how is it different from UIKit?

SwiftUI was introduced by Apple in 2019, and designed to help developers build user interfaces for their apps across all of Apple’s platforms, including iOS, macOS, watchOS, and tvOS. SwiftUI is different from UIKit in several ways:

  • SwiftUI is declarative, which means that developers can describe what they want the user interface to look like, and the framework handles the implementation details. This is different from UIKit, which is imperative, and requires developers to write code that specifies how the user interface should be created.
  • SwiftUI is cross-platform, which means that developers can use the same code to build user interfaces across all of Apple’s platforms. This is different from UIKit, which is specific to iOS.
  • SwiftUI is designed to work well with other frameworks such as Combine, Core Data, and CloudKit, which makes it easier for developers to build complete applications that integrate with other Apple services and technologies.
  1. What are the different types of views available in SwiftUI?

These are just some of the most commonly used view types in SwiftUI. There are many more available, and you can also create your own custom views to suit your specific needs.

  • Text: Displays a piece of text on the screen.
  • Image: Displays an image on the screen.
  • Button: Creates a button that users can tap to trigger an action.
  • TextField: Allows users to enter text input.
  • Toggle: Creates a switch that users can use to turn a setting on or off.
  • Slider: Allows users to select a value from a range by sliding a thumb across a track.
  • List: Displays a scrollable list of content, such as rows of text or images.
  • ScrollView: Allows users to scroll through a view that contains more content than can fit on the screen.
  • NavigationView: Provides a navigation interface for your app, with a stack of views that users can navigate through.
  • TabView: Displays a set of tabs, with each tab showing a different view.
  • VStack and HStack: These are layout views that allow you to stack views vertically or horizontally, respectively.
  • ZStack: Allows you to layer views on top of each other, creating a 3D-like effect.
  1. How do you handle user input in SwiftUI?

In SwiftUI, you can handle user input in a variety of ways, depending on the type of input and the context in which it occurs, and you can also create your own custom views and gestures to suit your specific needs. Here are some common approaches:

  • Use the Button view to create a button that the user can tap to trigger an action. You can attach a closure to the button using the action parameter, which will be executed when the button is tapped.
  • Use the TextField view to create a text input field that the user can type into. You can read the current value of the text field using a @State property, and update it in response to user input using the onChange modifier.
  • Use the Slider view to create a slider that the user can drag to select a value from a range. You can read the current value of the slider using a @State property, and update it in response to user input using the onChange modifier.
  • Use the Toggle view to create a switch that the user can flip to turn a setting on or off. You can read the current value of the toggle using a @State property, and update it in response to user input using the onChange modifier.
  • Use gesture recognizers, such as TapGesture, LongPressGesture, or DragGesture, to detect user input that doesn’t map directly to a specific control, such as taps, swipes, or drags. You can attach a closure to a gesture recognizer using the gesture modifier, which will be executed when the gesture is detected.
  • Use the NavigationLink view to create a link that the user can tap to navigate to a new view. You can attach a destination view to the link using the destination parameter, which will be displayed when the user taps the link.
  1. How do you navigate between views in SwiftUI?

In SwiftUI, you can navigate between views using several different techniques, depending on the specific requirements of your app. Here are some common approaches:

  • Use the NavigationView and NavigationLink views to create a navigation interface for your app. You can wrap your main view in a NavigationView, and then use NavigationLink views to create links to other views in your app. When the user taps a link, the destination view is pushed onto the navigation stack and displayed on the screen.
  • Use the sheet, popover, or fullScreenCover modifier to present a new view as a modal sheet on top of the current view. Modal views are typically used for transient tasks, such as displaying a settings screen or a login form. When the user is done with the modal view, they dismiss it by swiping it down or tapping a button.
  • Use the TabView view to create a tab bar interface for your app. A tab bar interface allows the user to switch between different sections or modes of your app by tapping on tabs at the bottom of the screen.
  • If none of the built-in navigation techniques fit your needs, you can create your own custom navigation solution using gesture recognizers and transitions. For example, you could create a swipe gesture that slides a new view in from the side, or a pinch gesture that zooms in to reveal a detail view.
  1. What is the difference between ObservableObject and StateObject in SwiftUI?

In SwiftUI, ObservableObject is a protocol that defines an object that can be observed and updated by SwiftUI, while StateObject is a property wrapper that provides a way to create and manage an instance of an ObservableObject within a view hierarchy.

You typically use StateObject when you need to create a new instance of an object that is owned by a specific view hierarchy, and you use ObservableObject when you need to share the state of an object across multiple views.

class User: ObservableObject {
    @Published var name = "John"
}

struct ContentView: View {
    @StateObject var user = User()
    
    var body: some View {
        VStack {
            Text("Hello, \(user.name)!")
            TextField("Enter your name", text: $user.name)
        }
    }
}
  1. What is the role of modifiers in SwiftUI, and how do you use them?

In SwiftUI, modifiers are used to modify the appearance or behavior of views. They allow you to customize various aspects of a view, such as its font, color, alignment, layout, and more.

Modifiers are applied to a view using a dot syntax, with the modifier name following the view it’s modifying. They can also be chained together to apply multiple modifications to a view.

Text("Hello, world!")
    .font(.headline)
    .padding()
  1. What is the purpose of a container view in SwiftUI, and how is it used?

In SwiftUI, a container view is a type of view that can contain other views, help you create more complex and customizable user interfaces. By nesting container views inside each other, you can create layouts that are flexible and adaptive to different screen sizes and orientations.

Examples of container views in SwiftUI include VStack, HStack, ZStack, List, and Form. They are useful for grouping related views together and controlling their layout and spacing. For example, the VStack container view can be used to stack views vertically, while the HStack container view can be used to stack views horizontally.

struct ContentView: View {
    var body: some View {
        VStack {
            Text("Hello")
                .font(.largeTitle)
                .foregroundColor(.blue)
            Text("World")
                .font(.title)
                .foregroundColor(.green)
        }
    }
}