【Xcode】【Swift】NSJSONSerializationのエラー"use of unresolved identifier","Extra argument 'Error' in call"
ひと昔前のSwiftの参考書でJSONを使う場合コードとして、以下のような内容が書いてあると思うのですが、今この通り書くとまあエラーが出ますね。
あらかじめ格納しておくJSONデータは以下の通り。
json.txt
["test1","test2","test3","test4"]
これを読み込んでデバッグエリアのコンソールに表示しようとする場合のViewController.swiftのコード。
(旧)ViewController.swift
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { let path = NSBundle.mainBundle().pathForResource("json",ofType:"txt") let data = NSData(contentsOfFile: path!) let jsonArray: NSArray = NSJSONSerialization.JSONObjectWithData(data!, options: nil, error:nil) as! NSArray for tmp in jsonArray { print("\(tmp)") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
おそらく、上記15行目のところで、Extra argument 'Error' in callというエラーが出ると思います。
これはスタック・オーバーフローのSwift 2を使うとNSJSONSerialization.JSONObjectWithData()でコンパイルエラー 'Extra argument 'error' in call' が発生するというページを参考にして解決できました。
エラー処理に際しては、do,try,catchの構文を使うみたいですね。
なのでerror:nilを消すと、'Nil is not compatible with expected argument type 'NSJSONReadingOptions'とか'Call can throw, but it is not marked with 'try' and the error is not handled'とかさらにエラーが出ますが、options: をnilではなくして冒頭にtryをつける。さらにdo{}catch{}を使います。
これでも、print("\(tmp)")のところで、use of unresolved identifierというエラーが出てどうにも困ります。
まあよくわからないのですが、doの{}カッコ内ならjsonArrayが定義されてるから同じカッコ内に入れてしまえばいいんじゃないかと思って、総合的に以下のように書き換えたらうまくいきました。
(新)ViewController.swift
import UIKit class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() // Do any additional setup after loading the view, typically from a nib. } override func viewWillAppear(animated: Bool) { let path = NSBundle.mainBundle().pathForResource("json",ofType:"txt") let data = NSData(contentsOfFile: path!) do{ let jsonArray: NSArray = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as! NSArray for tmp in jsonArray { print("\(tmp)") } } catch{ print("error") } } override func didReceiveMemoryWarning() { super.didReceiveMemoryWarning() // Dispose of any resources that can be recreated. } }
結果
test1
test2
test3
test4