本文介绍了NSStandardUserDefaults上的iOS / Swift 1.2 NSDictionray / Dictionary的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在旧Swift中,我曾经注册了一个.plist文件加载的默认值,如下所示。

In the 'old' Swift, I used to register my defaults loaded from a .plist file like this...

let prefs = NSBundle.mainBundle().pathForResource("UserDefaults", ofType: "plist");
let dict = NSDictionary(contentsOfFile: prefs!);
let defaults:NSDictionary! = dict?.valueForKey("defaults") as! NSDictionary;

NSUserDefaults.standardUserDefaults().registerDefaults(defaults);
NSUserDefaults.standardUserDefaults().synchronize();

在Swift 1.2下,我收到错误...

Under Swift 1.2, I get the error...

无法使用'(NSDictionary!)'类型的参数列表调用'registerDefaults'

所以有些事情发生了变化, Swift不再接受NSDictionary作为registerDefaults的参数。

So, something has changed and Swift no-longer accepts an NSDictionary as a parameter to registerDefaults.

所以,如何将NSDictionary转换为Dictionary对象,因为它们不可更换?

So, how can I convert my NSDictionary to a Dictionary object, given that they're no-longer interchangeable?

推荐答案

您需要从 NSDictionary 提供一个类型转换 [NSObject:AnyObject] -

You need to provide a type cast from NSDictionary to a [NSObject:AnyObject] -

使用

let prefs = NSBundle.mainBundle().pathForResource("UserDefaults", ofType: "plist");
let dict = NSDictionary(contentsOfFile: prefs!);
let defaults:NSDictionary! = dict?.valueForKey("defaults") as! NSDictionary
NSUserDefaults.standardUserDefaults().registerDefaults(defaults as [NSObject : AnyObject]);
NSUserDefaults.standardUserDefaults().synchronize();

这篇关于NSStandardUserDefaults上的iOS / Swift 1.2 NSDictionray / Dictionary的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-30 06:43