2016-04-15 89 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