📦 SwiftyLaunch Modules
🔗 SharedKit
Helper Functions
Check if in SwiftUI Preview

Check if code is being executed in a SwiftUI Preview

SharedKit Helper Function (SwiftyLaunch Module) - isPreview

SwiftUI Previews are helpful, but there are instances, where the executed code should be different when running in a preview.

For example, when using biometric authentication, you might want to skip the authentication step when showing persons account settings in a preview. You just want to fill it with some dummy data.

For this, we have introduced a convenient isPreview global computed variable. It simply returns a boolean value indicating whether the code is being executed in a SwiftUI preview or not.

Variable declaration:

isPreview.swift
public var isPreview: Bool {
    return ProcessInfo.processInfo.environment["XCODE_RUNNING_FOR_PREVIEWS"] == "1"
}

Here's an example on you might want to use it:

import SharedKit
import SwiftUI
 
struct YourAccountView: View {
 
    @State private var userFirstName: String
    @State private var userLastName: String
    @State private var age: Int
 
    // just an example, has nothing to do with the DB class from DBKit
    @EnvironmentObject var db: DB
 
    init() {
        if isPreview {
            // Fill with dummy data
            userFirstName = "John"
            userLastName = "Doe"
            age = 42
        } else {
            // Fill with actual data
            userFirstName = db.currentUser.firstName
            userLastName = db.currentUser.lastName
            age = db.currentUser.age
        }
    }
 
    var body: some View {
        VStack {
            Text("First Name: \(userFirstName)")
            Text("Last Name: \(userLastName)")
            Text("Age: \(age)")
        }
    }
}
 
#Preview {
    YourAccountView()
        .environmentObject(DB())
}