2 types of Life cycle of SwiftUI

SwiftUI has 2 types of lifecycle.

  • UIKit App Delegate
  • SwiftUI App

This post says about these life cycles.

Select the life cycle of app

You can select the life cycle of app when you create the project. Xcode 12 added the life cycle option into the project options dialog.

However, if you choose the template for the Multiplatform, this option will not appeared. Multiplatform template always use the SwiftUI App life cycle.

UIKit App Delegate

UIKit App Delegate use the UIKit to implement. The framework is different by OS.

  • UIKit App Delegate – iOS/iPadOS/tvOS
  • AppKit App Delegate – macOS
  • WatchKit App Delegate – watchOS

SwiftUI App

SwiftUI App can be used with Xcode 12 or later. SwiftUI App life cycle supports multiplatform with the same code. System requirement of SwiftUI App is below.

  • iOS/iPadOS 14.0 or later
  • macOS 11.0 or later
  • tvOS 14.0 or later
  • watchOS 7.0 or later

The code of SwiftUI App

The life cycle of the app is from launching app to terminate. The life cycle code must implement the code to show the ContentView. Xcode generates it. Generated codes implements following functions.

  1. Creating windows
  2. Creating scenes
  3. Place the ContentView

The code is simple and supports multiplatform.

@import SwiftUI

@main
struct MyApp: App {
    var body: some Scene {
        WindowGroup {
            ContentView()
        }
    }
}

@main

@main attribute represent that MyApp structure is an entry point of the program. Swift 5.3 introduced this attribute.

App

App protocol define the content of the app.

WindowGroup

WindowGroup is a container of the view hierarchy. WindowGroup use the view as a template and create the content view of each windows.

ContentView

First visible content of the app.

SwiftUI App vs UIKit App Delegate, which lifecycle should be used?

Think the system requirement of your app. If you create the new app and it supports iOS 13, you need to use the UIKit App Delegate.

Personally, I think you should use SwiftUI App for new apps. Because it is easy to support multiplatform.

 

Sponsored Links
Get the Latest News !