2

I've come across a problem and I'm struggling to understand why this happens. Whenever I try and pass my custom Swift error object using generics, I get an error when I try to access the localizedDescription property. I have some example code here, which demonstrates the issue:

import Foundation

enum CustomError: Swift.Error {
    case myCustomError

    var localizedDescription: String {
        return "Woop custom error string"
    }
}

func printMyError<T: Swift.Error>(error: T) {
    print(error.localizedDescription)
}

printMyError(error: CustomError.myCustomError) // <-- Fails
print(CustomError.myCustomError.localizedDescription) // <-- Works
3
  • @Martin R I'm not sure why you've marked this as duplicate. I've clearly stated that this is a problem when using generics. The article you've linked to does not mention generics at all. Commented Jan 25, 2018 at 9:44
  • 1
    The first linked-to Q&A explains how to make it work (by conforming to LocalizedError). The second one explains in detail why your printMyError(error: CustomError.myCustomError) "fails" – in short: because localizedDescription is not a protocol requirement of the Error protocol, and therefore statically dispatched. Commented Jan 25, 2018 at 9:47
  • My apologies. I didn't see the second link. You are correct, it does give me the solution. Thank you very much :) Commented Jan 25, 2018 at 10:16

0

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.