Swift ObservedObject 'self' 在 属性 访问 'userPreferences' 之前使用所有存储属性初始化

Swift ObservedObject 'self' used in property access 'userPreferences' before all stored properties are initialized

我遇到了以下问题,你能告诉我哪里错了吗?

import EventKit
import ServiceManagement

private struct PreferencesKeys {
    static let backgroundIsTransparent = "backgroundIsTransparent"
    static let isDarkMode = "isDarkMode"
}

class UserPreferences: ObservableObject {
    static let instance = UserPreferences()
    
    private init() {
        // This prevents others from using the default '()' initializer for this class.
    }
    
    private static let defaults = UserDefaults.standard
    
    @Published var backgroundIsTransparent: Bool = {
        guard UserDefaults.standard.object(forKey: PreferencesKeys.backgroundIsTransparent) != nil else {
            return true
        }
        return UserDefaults.standard.bool(forKey: PreferencesKeys.backgroundIsTransparent)
    }() {
        didSet {
            UserPreferences.defaults.set(backgroundIsTransparent, forKey: PreferencesKeys.backgroundIsTransparent)
        }
    }
    
    @Published var isDarkMode: Bool = {
        guard UserDefaults.standard.object(forKey: PreferencesKeys.isDarkMode) != nil else {
            return true
        }
        return UserDefaults.standard.bool(forKey: PreferencesKeys.isDarkMode)
    }() {
        didSet {
            UserPreferences.defaults.set(isDarkMode, forKey: PreferencesKeys.isDarkMode)
        }
    }
    
}

这是一个常见的错误。

您将在初始化 statusItem 之前修改 popover。这违反了规则,这就是错误所说的。

首先初始化statusItem然后设置popover的背景色。

我会初始化statusItem甚至

let statusItem = NSStatusbar.system.status...

问题中的代码(文本)无关紧要。