如何在不重复代码的情况下在Swift中指定多个包路径?

时间:2016-12-27 19:02:13

标签: swift xcode path bundle plist

可能是一个简单的问题,如何为swift指定多个包路径而无需多次复制粘贴此代码?

 if let path = Bundle.main.path(forResource: "extra-1", ofType: "plist") {
        if let dictArray = NSArray(contentsOfFile: path) {
            for item in dictArray {
                if let dict = item as? NSDictionary {
                    let name = dict["identifier"] as! String
                    let species = dict["species"] as! Int

                    let animal = Animal(name: name, speciesId: species)
                    pokes.append(animal)
                    print("Name: \(name) Id: \(species)")
                }
            }
        }
    }

我希望swift能够从多个plist文件中访问相同的dict项目,但到目前为止,我唯一的解决方案是为17个以上的文件重复此代码。任何举行都将是赞赏

1 个答案:

答案 0 :(得分:1)

尝试这样的事情:

extension Animal {
    init(fromDict dict: [String: Any]) {
        self.init(
            name: dict["identifier"] as! String,
            species: dict["species"] as! Int
        )
    }
}

let resourceNames = [
    "extra-1",  "extra-2", /* ... */  "extra-n"
]

let pokes = resourceNames.flatMap { resourceName -> [Animal] in
    guard let plistPath = Bundle.main.path(forResource: resourceName, ofType: "plist") else {
        fatalError("Nil path") //TODO: add error handling!
    }
    guard let array = NSArray(contentsOfFile: plistPath) else { fatalError("File read error") }

    let arrayOfDicts = array.map{ element -> [String: Any] in
        guard let dict = element as? [String: Any] else { fatalError("Element is not a dictionary!") }
        return dict
    }

    let newPokes = arrayOfDicts.map(Animal.init(fromDict:))
    print(newPokes)
    return newPokes
}