Guest User

Untitled

a guest
Mar 19th, 2020
105
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Swift 0.92 KB | None | 0 0
  1. import UIKit
  2.  
  3. extension UIColor {
  4.     func components() -> [CGFloat] {
  5.         var r = CGFloat(0)
  6.         var g = CGFloat(0)
  7.         var b = CGFloat(0)
  8.         var a = CGFloat(0)
  9.         getRed(&r, green: &g, blue: &b, alpha: &a)
  10.         return [r,g,b,a]
  11.     }
  12.     convenience init?(components: [CGFloat]) {
  13.         guard components.count == 4 else {
  14.             return nil
  15.         }
  16.         self.init(red: components[0],
  17.                   green: components[1],
  18.                   blue: components[2],
  19.                   alpha: components[3])
  20.     }
  21. }
  22.  
  23. let colors: [UIColor] = [.cyan, .magenta, .yellow, .black]
  24. let serialized = colors.map { $0.components() }
  25.  
  26. UserDefaults.standard.set(serialized, forKey: "SerializedColors")
  27. let restored = UserDefaults.standard.value(forKey: "SerializedColors") as? [[CGFloat]]
  28.  
  29. for components in restored ?? [] {
  30.     print(UIColor(components: components) ?? "not a color")
  31. }
Advertisement
Add Comment
Please, Sign In to add comment