0
votes

I am getting an error on below code while I updating my code to latest Swift syntax.

  • Binary operator '==' cannot be applied to operands of type '()' and 'Bool'
  • Call can throw, but it is not marked with 'try' and the error is not handled

enter image description here

Please help me in finding the solution.

6
You should post actual code instead of screenshots. See here for details. Thank you. - Pang
@Gaurav writeToFile does not return a Bool. It throws an error. You should use do try catch error handling - Leo Dabus

6 Answers

2
votes

You have to write in do catch block because it throws exception

do {
    try str.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
}
catch {

}

You can also catch the error as follows :

do {
    try str.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
}
catch let error as NSError {
    print(error.description)
}

You can also go through guard and defer : http://nshipster.com/guard-and-defer/ Which are new concept in swift

1
votes

writeToFile method throws exception. Use this block

  do {
      try str.writeToFile(filename, atomically: true, encoding: NSUTF8StringEncoding)
     }
catch {
// failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
      }
0
votes

For solving of your issue try to use try catch construct.

     do {
       try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
     }
     catch
     {

     }
0
votes

The function writeToFilePath(path, atomically:, encoding:) does not return anything (it's return type is Void or ()) and you are trying to compare nothing to a boolean value.

The second error line explains that this routine throws an error if it fails. You need to use Swift's error handling mechanisms to handle the error rather than trying to compare the function result against a bool.

0
votes

In Swift,it won't return Bool no longer.Here is the description in Documentation:

func writeToFile(_ path: String,
      atomically useAuxiliaryFile: Bool,
        encoding enc: UInt) throws

As it will throw errors,you should try and ignore error like this:

try! contentsOfFile.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)

Or you catch and handle error:

do {
    try contentsOfFile.writeToFile("yourPath", atomically: true, encoding: NSUTF8StringEncoding)
} catch let error {
    // handle error here
}
0
votes

The above answers are all correct!!! These calls may throw an exception.

do {
    contentsOfFile str.writeToFile(path, atomically: true, encoding:    NSUTF8StringEncoding)
}
catch {

}