0

I want to catch the reason of error in map function and notify it by print.

I tried to use double quotation for emphasizing the reason inside my custom error message like this;

enum MyError: Error{
    case creationError(_ message: String)
}

func creation() -> [Float]?{
    ...

    do{
         let arr_str = line.split(separator: parser.delimiter, omittingEmptySubsequences: false)    
         let arr = try arr_str.map{
                   (str) -> Float in
                   guard let val = Float(str) else{
                       throw MyError.creationError("could not convert string to float: \"\(str)\"")
                   }
                   return val
               }
         return arr    
    }
    catch{
         print("\(error)")
         return nil
    }

}

expected output is could not convert string to float: "" but console output was like this;

creationError("could not convert string to float: \"\"")

if I try;

throw MyError.creationError("could not convert string to float: "\(str)"")

but Xcode says;

Expected ',' separator

How can l escape double quotation inside my custom error message? Or How can I get error message only in catch block?

jjjkkkjjj
  • 51
  • 1
  • 7
  • The backslashes are an artifact of *printing* the error, they are not part of the string. For customizing the output of your error, see for example [How to provide a localized description with an Error type in Swift?](https://stackoverflow.com/q/39176196/1187415). – Martin R May 12 '20 at 07:16

1 Answers1

1

Unfortunately, Swift uses debugDescription for some automatically generated String representation, which adds escaping symbol before double-quote.

In such a case, you can create your own string representation with conforming to CustomStringConvertible.

extension MyError: CustomStringConvertible {
    var description: String {
        switch self {
        case .creationError(let message):
            return "creationError(\(message))"
        }
    }
}
OOPer
  • 47,149
  • 6
  • 107
  • 142