我完全是Swift的菜鸟,但是我觉得这是必须的,而且有人在我之前做到了。
这是我的问题:
我有一个plist
,其中包含一堆游戏中的角色类。每个字符都唯一地升级。理想情况下,我会将Level_Progression
做成一个数组,该数组包含我从plist
导入的字符类字典中的10个子字典。因此,随着角色级别的提高,该应用会查看Level_Progression
细分,以根据角色级别更新某些字段。
如何导入嵌套的数组和子字典,以便我的应用可以理解数据的关系?
以下是带有一些占位符数据的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">
<array>
<dict>
<key>ClassName</key>
<string>Barb</string>
<key>Level_Progression</key>
<array>
<dict>
<key>Level</key>
<integer>1</integer>
<key>HP_Mult</key>
<integer>3</integer>
</dict>
<dict>
<key>Level</key>
<integer>2</integer>
<key>HP_Mult</key>
<integer>3</integer>
</dict>
<dict>
<key>Level</key>
<integer>3</integer>
<key>HP_Mult</key>
<integer>5</integer>
</dict>
<dict>
<key>Level</key>
<integer>4</integer>
<key>HP_Mult</key>
<integer>5</integer>
</dict>
<dict>
<key>Level</key>
<integer>5</integer>
<key>HP_Mult</key>
<integer>9</integer>
</dict>
</array>
</dict>
<dict>
<key>ClassName</key>
<string>Cleric</string>
<key>Level_Progression</key>
<array>
<dict>
<key>Level</key>
<integer>1</integer>
<key>HP_Mult</key>
<integer>3</integer>
</dict>
<dict>
<key>Level</key>
<integer>2</integer>
<key>HP_Mult</key>
<integer>3</integer>
</dict>
<dict>
<key>Level</key>
<integer>3</integer>
<key>HP_Mult</key>
<integer>5</integer>
</dict>
<dict>
<key>Level</key>
<integer>4</integer>
<key>HP_Mult</key>
<integer>5</integer>
</dict>
<dict>
<key>Level</key>
<integer>5</integer>
<key>HP_Mult</key>
<integer>9</integer>
</dict>
</array>
</dict>
</array>
</plist>
这是我的导入脚本现在的样子,我知道它不起作用。我将其保存在单独的快速文件中,然后计划是在导入所有数据后从struct
调用ViewController
import Foundation
struct CharClass {
let className: String
let level_Progress: Array<Dictionary<String, Int>>
let level: Dictionary<String, Int>.Element
let hp_Mult: Dictionary<String, Int>.Element
static func classesList(_ fileName: String) -> [CharClass] {
var charClasses = [CharClass]()
if let classList = NSArray(contentsOfFile: fileName) as? [[String: Any]] {
for dict in classList {
if let charClass = CharClass(dictionary: dict) {
charClasses.append(charClass)
}
}
}
return charClasses
}
init?(dictionary: [String: Any]) {
guard let className = dictionary["ClassName"] as? String,
let level_Progress = dictionary["Level_Progress"] as? Array<Dictionary<String, Int>>,
let level = dictionary["Level"] as? Dictionary<String, Int>.Element,
let hp_Mult = dictionary["HP_Mult"] as? Dictionary<String, Int>.Element else {
return nil
}
self.className = className
self.level_Progress = level_Progress
self.level = level
self.hp_Mult = hp_Mult
}
}