Paul
Paul

Reputation: 4438

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

enter image description here

I'm having the following problem can you tell me where I'm wrong?

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)
        }
    }
    
}

Upvotes: 0

Views: 118

Answers (1)

vadian
vadian

Reputation: 285092

This is a common mistake.

You are going to modify popover before having initialized statusItem. This breaks the rules and this is what the error says.

First initialize statusItem then set the background color of popover.

I would initialize statusItem even

let statusItem = NSStatusbar.system.status...

The code (text) in the question is irrelevant.

Upvotes: 1

Related Questions