Xcode 7 beta 给出错误。

Xcode 7 beta gives error.

它之前是有效的。但在 Xcode 7 Beta 中给出错误。请帮助我

private func htmlStringWithFilePath(path: String) -> String? {

        // Error optional for error handling
        var error: NSError?

        // Get HTML string from path
        let htmlString = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: &error)

        // Check for error
        if let error = error {
            printLog("Lookup error: no HTML file found for path, \(path)")
        }

        return htmlString! as String
    }

现在给出 2 个错误。

  1. let htmlString = NSString(contentsOfFile: 路径, 编码: NSUTF8StringEncoding,错误:&error) ERROR 找不到 接受参数列表的 NSString 类型的初始值设定项 类型(....)
  2. printLog("Lookup error: no HTML file found for path, (path)") 错误使用未解析的标识符 printlog

在Swift 2 中有一个新的错误处理模型,带有try 和catch(几乎在整个Foundation/Cocoa 中)。这是一个工作示例:

private func htmlStringWithFilePath(path: String) -> String? {

    // Get HTML string from path
    // you can also use String but in both cases the initializer throws
    // so you need the do-try-catch syntax
    do {
        // use "try"
        let htmlString = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)
        // or directly return
        return htmlString

    // Check for error
    } catch {
        // an "error" variable is automatically created for you

        // in Swift 2 print is now used instead of println.
        // If you don't want a new line after the print, call: print("something", appendNewLine: false)
        print("Lookup error: no HTML file found for path, \(path)")
        return nil
    }
}