Skip to content

Instantly share code, notes, and snippets.

@vmanot
Last active May 6, 2018 09:20
Show Gist options
  • Save vmanot/090f88b2a4329c1e0daa to your computer and use it in GitHub Desktop.
Save vmanot/090f88b2a4329c1e0daa to your computer and use it in GitHub Desktop.
//
// Copyright (c) Vatsal Manot
//
import Foundation
import Swift
public func type<T>(x: T) -> T
{
return x
}
private var storage = NSUserDefaults.standardUserDefaults()
public struct Preferences
{
public static var storage: NSUserDefaults
{
return NSUserDefaults.standardUserDefaults()
}
}
extension Preferences
{
public static func get(key: String) -> AnyObject?
{
return storage.objectForKey(key)
}
public static func get<T: AnyObject where T: NSCoding>(key: String, type: T.Type = type(T)) -> T?
{
return storage.objectForKey(key) as? T
}
public static func get<T: _ObjectiveCBridgeable where T._ObjectiveCType: NSCoding>(key: String, type: T.Type = type(T)) -> T?
{
return storage.objectForKey(key) as? T
}
}
extension Preferences
{
public static func set<T: AnyObject where T: NSCoding>(value: T, forKey key: String)
{
storage.setObject(value, forKey: key)
}
public static func set<T: _ObjectiveCBridgeable where T._ObjectiveCType: NSCoding>(value: T, forKey key: String)
{
storage.setObject(value as? T._ObjectiveCType, forKey: key)
}
}
extension Preferences
{
public static func remove(key: String)
{
storage.removeObjectForKey(key)
}
}
extension Preferences
{
public static func synchronize()
{
storage.synchronize()
}
}
Preferences.set([NSData()], forKey: "MyKey1")
Preferences.get("MyKey1", type: type([NSData]))
Preferences.get("MyKey1") as [NSData]?
func crunch1(value: [NSData])
{
println("Om nom 1!")
}
crunch1(Preferences.get("MyKey1")!)
Preferences.set(NSArray(object: NSData()), forKey: "MyKey2")
Preferences.get("MyKey2", type: type(NSArray))
Preferences.get("MyKey2") as NSArray?
func crunch2(value: NSArray)
{
println("Om nom 2!")
}
crunch2(Preferences.get("MyKey2")!)
Preferences.set([[String:[Int]]](), forKey: "MyKey3")
Preferences.get("MyKey3", type: type([[String:[Int]]]))
Preferences.get("MyKey3") as [[String:[Int]]]?
func crunch3(value: [[String:[Int]]])
{
println("Om nom 3!")
}
crunch3(Preferences.get("MyKey3")!)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment