我正在尝试在Swift中实现对Array的扩展,以便能够从plist文件初始化,我正在尝试使用NSPropertyListReadOptions
extension Array {
static func arrayFromPlistWithName (filename: String) -> [[String:AnyObject]]? {
let path = NSBundle.mainBundle().pathForResource(filename, ofType: "plist")!
let url = NSURL(fileURLWithPath: path)
let data = NSData(contentsOfURL: url)
let opts = NSPropertyListReadOptions(rawValue: NSPropertyListMutabilityOptions.MutableContainersAndLeaves.rawValue)
let plist = try! NSPropertyListSerialization.propertyListWithData(data!, options: opts, format: nil)
return plist as? [[String:AnyObject]]
}
}
以及我如何使用它:
let a:[[String:AnyObject]]? = Array.arrayFromPlistWithName("countries")
但我可以提出错误:
Cannot convert value of type '[[String : AnyObject]]?' to specified type '[[String : AnyObject]]?'
我的问题是如何让它工作以及如何处理所有错误,因为我使用了大量的力量展开,这可能是导致崩溃的原因
答案 0 :(得分:0)
尝试这样的事情:
enum ArrayFromPlistError: ErrorType {
case InvalidPlist
}
extension Array {
static func readArray(FromPlistNamed name: String) throws -> [AnyObject] {
let path = NSBundle.mainBundle().pathForResource(name, ofType: "plist")!
if let array = NSArray(contentsOfFile:path) {
return array as AnyObject as! [AnyObject]
}
else {
throw ArrayFromPlistError.InvalidPlist
}
}
}