2016-01-09 84 views
0

我得到一個錯誤:錯誤斯威夫特與方法loadJSONFromBundle

Type 'Dictionary' has no member 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() 
        } 
       } 
      } 
     } 
    } 
} 
+2

沒有'loadJSONFromBundle'這樣的方法。你在哪裏看到這樣的方法記錄? – rmaddy

回答

0

.loadJSONFromBundle不是Dictionary中的默認方法。這可以通過擴展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 
     } 
    } 
}