2015-07-01 97 views
0

它以前工作。但在Xcode 7 Beta中出現錯誤。請幫助我Xcode 7測試版給出錯誤。

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. 讓htmlString =的NSString(contentsOfFile:路徑,編碼: NSUTF8StringEncoding,錯誤:&誤差) ERROR找不到一個 初始化類型的NSString接受 類型的參數列表(....)
  2. PRINTLOG( 「查找錯誤:找到的路徑中沒有HTML文件,(路徑)」) ERROR使用未解決的標識符打印日誌的

回答

0

在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 
    } 
} 
+0

謝謝.. :)它正在工作:) – davudi