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
JeremyP
  • 84,577
  • 15
  • 123
  • 161
Welton122
  • 1,101
  • 2
  • 13
  • 28
  • @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. – Welton122 Jan 25 '18 at 09: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. – Martin R Jan 25 '18 at 09:47
  • My apologies. I didn't see the second link. You are correct, it does give me the solution. Thank you very much :) – Welton122 Jan 25 '18 at 10:16

0 Answers0