Swift初始化字典数组

时间:2016-04-15 11:37:45

标签: arrays swift dictionary

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

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

这是我尝试实现的目标,但将数组作为可在所有函数中使用的全局变量。

Image

2 个答案:

答案 0 :(得分: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")
}

答案 1 :(得分: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

相关问题