Swift2: Unable to call initializer for type 'NSString'

I am new to Swift development. I just converted the existing working code to swift2, updating Xcode 7 with 6.

var err: NSError? let template = NSString(contentsOfFile: path!, encoding: NSUTF8StringEncoding, error: &err) as! String let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: NSStringCompareOptions.allZeros, range: nil) if err != nil { return false } 

Then, I received this error message:

 Cannot invoke initializer for type 'NSString' with an argument list of type '(contentsOfFile: String, encoding: UInt, error: inout NSError?)' 

Do you have any ideas? Thank you very much!

+1
source share
2 answers

You must use the string type Swift. You also need to implement Swift 2.0 to try to handle the error. Try it like this:

 let template = try! String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: [], range: nil) 

If you want to handle the error:

 do { let template = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) let iframe = template.stringByReplacingOccurrencesOfString("{{VIDEO_ID}}", withString: id, options: [], range: nil) } catch let error as NSError { print(error.localizedDescription) } 
+3
source

To handle the error, you must use the Swift 2 do-try-catch syntax:

 do { let template = try String(contentsOfFile: path!, encoding: NSUTF8StringEncoding) // Use the template } catch let error as NSError { // Handle the error } 

Definitely read the docs on this as it shows several other ways to handle errors - for example, try? will give you an option in case of any error, and try! will block the propagation of errors (although you will get a runtime error if an error occurs).

0
source

Source: https://habr.com/ru/post/984151/


All Articles