xcodeでiOSゲーム作りを始めました。
SpriteKitの使い方を学ぶべく、rayさんのホームページのチュートリアルを勉強していたのですが、
JSONファイルのデータをコード上の辞書型データに格納する過程でよくわからないことが起きたので質問しました。
参考です↓
https://www.raywenderlich.com/125311/make-game-like-candy-crush-spritekit-swift-part-1
extension機能を用いて、Dictionary型を拡張(?)しました。
拡張した関数を用いて、辞書型データのdictionaryにJSONファイルのデータを格納したつもりなのですが、
中身を確認すると何も入っていませんでした。
なぜ何も入っていないのか、どうすれば改善されるのか、教えて欲しいです。
よろしくお願いします。
###写経した内容
swift
1//Extension.swiftにて 2extension Dictionary{ 3 static func loadJSONFromBundle(filename:String) -> Dictionary<String,AnyObject>?{ 4 var dataOK: Data = Data() 5 var dictionaryOK:NSDictionary = NSDictionary() 6 7 if let path = Bundle.main.path(forResource:filename,ofType:"json"){ 8 do{ 9 let data = try Data(contentsOf:URL(fileURLWithPath:path),options:NSData.ReadingOptions())as Data! 10 } 11 catch{ 12 print("Could not load level file: \(filename),error: \(error)") 13 return nil 14 } 15 16 do{ 17 let dictionary = try JSONSerialization.jsonObject(with: dataOK,options:JSONSerialization.ReadingOptions())as AnyObject! 18 dictionaryOK = (dictionary as! NSDictionary as? Dictionary<String,AnyObject>)! as NSDictionary 19 } 20 catch{ 21 print("Level file '\(filename)' is not valid JSON: \(error)") 22 return nil 23 } 24 } 25 return dictionaryOK as? Dictionary<String,AnyObject> 26 } 27} 28 29 30//別swiftファイルで実行しようとしたところ 31 32filename = "Level_1" 33 34guard var dictionary = Dictionary<String,AnyObject>.loadJSONFromBundle(filename:filename)else{return}//else文実行されず 35 print(dictionary)//[:] 36 37 guard let tilesArray = dictionary["tiles"] as? [[Int]] else{return}//else文実行される 38 39
swift
1//Level_1.jsonにて 2{ 3 "tiles" : [ [0, 1, 1, 0, 0, 0, 1, 1, 0 ], 4 [1, 1, 1, 1, 1, 1, 1, 1, 1 ], 5 [1, 1, 1, 1, 1, 1, 1, 1, 1 ], 6 [1, 1, 1, 1, 1, 1, 1, 1, 1 ], 7 [0, 0, 1, 1, 1, 1, 1, 0, 0 ], 8 [1, 1, 1, 1, 1, 1, 1, 1, 1 ], 9 [1, 1, 1, 1, 1, 1, 1, 1, 1 ], 10 [1, 1, 1, 1, 1, 1, 1, 1, 1 ], 11 [0, 1, 1, 0, 0, 0, 1, 1, 0 ] ], 12 13 "targetScore" : 1000, 14 "moves" : 15, 15} 16 17
なお、コンソールには
[:]
以外出力されていません。
Xcode:8.3.2
Swift:3.x(3しかわかりませんが、最新のはずです)
macOS Sierra:10.12.4
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。
2017/05/09 00:44 編集
2017/05/10 07:53