Looking for swift syntax help to convert/represent an Error?

I’ve implemented a protocol called DescribedError that is implemented by NSError.

I’m creating a URLSession data task thusly:

        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in

 

error is defined as being of type Error?

In practice error is a nullable NSError

 

I want to create a variable called finalError of type DescribedError?

 

I’ve added code so NSError implements DescribedError

 

extension NSError: DescribedError {
    func title() -> String {
        return "myTitle"
    }

    func message() -> String {
  return "myMessage"
    }
}

 

now, to my question…

 

When I do this:

        let session = URLSession.shared
        let task = session.dataTask(with: request) { (data, response, error) in

               let finalError: DescribedError? = error

the compiler sez:

Cannot convert value of type ‘Error?’ to specified type ‘DescribedError?’

Insert ‘ as! DescribedError’

 

But I’d rather not do this forced conversion, so I tried doing this:

            var finalError: DescribedError?
            if let error = error as? DescribedError {
                finalError = error
            }

compiler sez:

Conditional downcast from ‘Error?’ to ‘DescribedError’ is a bridging conversion; did you mean to use ‘as’?

 

so I try doing this:

            var finalError: DescribedError?
            if let error = error as DescribedError {
                finalError = error
            }

but the compiler now sez:

‘Error?’ is not convertible to ‘DescribedError’; did you mean to use ‘as!’ to force downcast?

Replace ‘as’ with ‘as!’

 

 

basically, I want to do something like:

 

let finalError: DescribedError = error implements DescribedError ? error : nil

 

Is there a way to do this that does not generate a compiler warning or error? (or using a forced unwrap)

 

thanks,

 

Mike

Powered by WPeMatico

You may also like...

Comments are closed.