Since I am quite inexperienced in Swift/Foundation and since there is a doubt about the actual use case, I feel attaching a MWE of what I intend to do is probably beneficial.
import Foundation
let key = "AppleInterfaceStyle"
class Observer: NSObject {
override init() {
super.init()
UserDefaults.standard.addObserver(self, forKeyPath: key, options: [NSKeyValueObservingOptions.new], context: Optional<UnsafeMutableRawPointer>.none)
}
deinit {
UserDefaults.standard.removeObserver(self, forKeyPath: key, context: Optional<UnsafeMutableRawPointer>.none)
}
override func observeValue(forKeyPath keyPath: String?, of object: Any?, change: [NSKeyValueChangeKey : Any]?, context: UnsafeMutableRawPointer?) {
let result = change?[.newKey] ?? ""
var theme : String = String(describing: result)
if (theme == "<null>") {
theme = "Light"
}
print("swift: detected \(theme)")
}
}
public func main() -> Void {
// Begin observing standardUserDefaults.
let observer = Observer()
_ = observer // silence "constant never used" warning
RunLoop.current.run()
}
//main() //run from main thread with stdin
// run from background
DispatchQueue.global(qos: .background).async {
main()
}
When running in this version, the script returns immediately. Uncommenting the direct call to main() results in the script functioning properly and printing to the stdout whenever the Appearance of the system is changed from System Preferences.