SwiftUI is the new user interface toolkit introduced to create apps across all Apple platforms using Swift. Before SwiftUI was introduced, user interfaces were built using UIKit, Interface Builder, and Storyboards.
The problem with Interface Builders and Storyboards is that they use XML and it is not easily editable or readable. It is very difficult to review it in source control. Moreover, the XML generated may not always be in sync with the code. For example, When we remove an IBAction from the code, a reference to that action remains in the Interface Builder until it is manually removed. The app will run successfully, but when that particular action gets performed, the app will crash. SwiftUI solves these problems as whenever the UI is modified manually, Xcode automatically generates the code, i.e. the code and UI are always in sync.
SwiftUI makes use of declarative syntax, i.e., it enables developers to specify how the UI should appear and how to respond when a state changes. The declarative syntax simplifies and makes the code easier to read.
Advantages of SwiftUI.
- SwiftUI's live preview feature provides instant feedback on the UI you're coding, speeding up the development process.
- With minor modifications, the same SwiftUI code can be used for all Apple platforms such as WatchOS, iPadOS, tvOS, macOS, and so on.
- SwiftUI is compatible with the existing UIKit. It also provided a way to use existing UIKit elements alongside the SwiftUI code.
Disadvantages of SwiftUI
- SwiftUI is only compatible with iOS 13.0, iPadOS 13.0, macOS 10.15, Mac Catalyst 13.0, tvOS 13.0, watchOS 6.0 or on later versions of those platforms.
- Not all the features available in UIKit are present in SwiftUI as it is relatively new and still in development.
Code Comparison with Example
Let us look at the code comparison to create the following example using SwiftUI and UIKit. The following example, when created using SwiftUI takes very few lines as compared to UIKit.
To know and learn more about SwiftUI, here is the link to the official tutorial and documentation provided by Apple.
Documentation - https://developer.apple.com/documentation/SwiftUI