Last active
March 12, 2022 19:12
-
-
Save pascalpp/b001e303e77677ff1223c1da27305a4f to your computer and use it in GitHub Desktop.
Swift 5 extension to add NSColor support to UserDefaults
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Cocoa | |
extension UserDefaults { | |
func set(_ color: NSColor, forKey: String) { | |
if let data = try? NSKeyedArchiver.archivedData(withRootObject: color, requiringSecureCoding: false) { | |
self.set(data, forKey: forKey) | |
} | |
} | |
func color(forKey: String) -> NSColor? { | |
guard | |
let storedData = self.data(forKey: forKey), | |
let unarchivedData = try? NSKeyedUnarchiver.unarchivedObject(ofClass: NSColor.self, from: storedData), | |
let color = unarchivedData as NSColor? | |
else { | |
return nil | |
} | |
return color | |
} | |
} |
Author
pascalpp
commented
May 11, 2019
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment