【问题标题】:Error in Swift with method loadJSONFromBundle使用方法 loadJSONFromBundle 的 Swift 错误
【发布时间】:2016-01-09 02:18:35
【问题描述】:

我收到一个错误:

类型“字典”没有成员 loadJSONFromBundle。

知道它有什么问题吗?

init(filename: String) 
{
    if let dictionary = Dictionary<String, AnyObject>.loadJSONFromBundle(filename) {
        if let tilesArray = dictionary["tiles"] as? [[Int]] {
            for (row, rowArray) in enumerate(tilesArray as! [[Int]]) {
                let tileRow = NumRows - row - 1
                for (column, value) in enumerate(rowArray) {
                    if value == 1 {
                        tiles[column, tileRow] = Tile()
                    }
                }
            }
        }
    }
}

【问题讨论】:

  • 没有loadJSONFromBundle这样的方法。您在哪里看到这样的方法记录在案?

标签: ios json swift2


【解决方案1】:

.loadJSONFromBundle 不是 Dictionary 中的默认方法。这可以通过扩展字典来添加。这是我在 Swift 3 中的实现:

import Foundation

extension Dictionary {
    static func loadJSONFromBundle(filename: String) -> Dictionary<String, AnyObject>? {
        if let path = Bundle.main.path(forResource: filename, ofType: "json") {
            var error: NSError?
            do {
                let data: NSData? = try NSData(contentsOf: URL(fileURLWithPath: path), options: NSData.ReadingOptions())
                if let data = data {
                    let dict: Any? = try JSONSerialization.jsonObject(with: data as Data, options: JSONSerialization.ReadingOptions())
                    if let dict = dict as? Dictionary<String, AnyObject> {
                        return dict
                    }
                    else {
                        print("file '\(filename)' is not vaild JSON: \(error!)")
                        return nil
                    }
                }
            }
            catch {
                print("could not load file '\(filename)'")
                return nil
            }
        }
        else {
            print("could not find level file '\(filename)'")
            return nil
        }
    }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2019-01-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多