Life is Really Short, Have Your Life!!

ござ先輩の主に技術的なメモ

Swift2.0でファイルの読み込み

Swift2.0で構文が変わっている。昔はこんなシグネチャだった。

//1.2
NSString(contentsOfFile: path, 
encoding: NSUTF8StringEncoding, 
error: nil)

//2.0
NSString(contentsOfFile: path, 
encoding: NSUTF8StringEncoding) throws

try〜catch構文が入ったことで、NSErrorを引数に入れるのではなく自分でtry〜catchするかrethrowするかにしなさい、という話のようだ。

プロジェクトにsample.jsonというファイルを直下に入れてやってみました。こんな感じで読み込めます。

        if let filePath = NSBundle.mainBundle().
                  pathForResource("sample", ofType: "json") {
            do {
                let str = try String(contentsOfFile: filePath,
                    encoding: NSUTF8StringEncoding)
            }
            catch let error as NSError {
                print(error.localizedDescription)
            }
        }