2016-04-15 131 views
-2

我有一个字典数组plist,我试图初始化一个数组,然后我可以访问数组中的每个字典,但不知道如何。Swift初始化字典数组

在Objective-C我通常用NSArray *array = [plist objectForKey:@"Root"];然后用NSDictionary *dictionary = [array objectAtIndex:i];然后NSString *string = [dictionary [email protected]"title"];

这就是我想要实现但与阵列可以在所有的函数中使用全局变量。

Image

回答

1

根据你的财产清单文件,你可以使用这个

// check the URL (URL related API is recommended) 
if let tipsURL = NSBundle.mainBundle().URLForResource("Tips", withExtension:"plist") { 
    // read the property list file and cast the type to native Swift 'Dictionary' 
    let tipsPlist = NSDictionary(contentsOfURL: tipsURL) as! [String:AnyObject] 
    // get the array for key 'Category 1', 
    // casting the result to '[[String:String]]` avoids further type casting 
    let categoryArray = tipsPlist["Category 1"] as! [[String:String]] 
    // iterate thru the expected array and print all values for 'Title' and 'Tip' 
    for category in categoryArray { 
    print(category["Title"]!) 
    print(category["Tip"]!) 
    } 
} else { 
    // if the plist file does not exist, give up 
    fatalError("Property list file Tips.plist does not exist") 
} 

或考虑在根对象

if let tipsURL = NSBundle.mainBundle().URLForResource("Tips", withExtension:"plist") { 
    let tipsPlist = NSDictionary(contentsOfURL: tipsURL) as! [String:AnyObject] 
    for (_, categoryArray) in tipsPlist { 
    for category in categoryArray as! [[String:String]] { 
     print(category["Title"]!) 
     print(category["Tip"]!) 
    } 
    } 
} else { 
    fatalError("Property list file Tips.plist does not exist") 
} 
+0

谢谢,这很好,正是我想要的,最后如何我会声明categoryArray,以便可以从其他函数访问它。 – Sami

+0

实际上,包含类别('Category 1','Category 2'等)的对象是一个字典,而不是一个数组。在给定属性列表的问题中,如果'plist'是根对象,'NSArray * array = [plist objectAtIndex:0]'根本无法工作。 – vadian

+0

刚刚实现的第一个对象也是一本字典,修正了问题。 – Sami

0
var aDict: NSDictionary? 
if let path = NSBundle.mainBundle().pathForResource("file", ofType: "plist") { 
    aDict = NSDictionary(contentsOfFile: path) 
} 

if let aDict = aDict { 
    let str = aDict["title"] 
    print(str) // prints "I am a title." 
} 

要的.plist文件如

<?xml version="1.0" encoding="UTF-8"?> 
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> 
<plist version="1.0"> 
<dict> 
    <key>title</key> 
    <string>I am a title.</string> 
</dict> 
</plist> 

PS:Global variables are bad

+0

我说我的plist中的图像的所有密钥。 – Sami

+0

Stackoverflow不是一个编码服务。 :-) –

+0

我明白了,我清楚知道如何在Objective-C中做到这一点,尝试端口到Swift,在这两天,所以最终诉诸于stackoverflow – Sami