NSUserDefaults in Swift - implementing type safety

后端 未结 2 1908
独厮守ぢ
独厮守ぢ 2021-02-02 01:43

One of the things that bugs me about Swift and Cocoa together is working with NSUserDefaults, because there is no type information and it is always necessary to cast the result

2条回答
  •  感情败类
    2021-02-02 02:39

    I don't mean to brag but ... oh who am I kidding, I totally do!

    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")!)
    

提交回复
热议问题