Uploaded image for project: 'Swift'
  1. Swift
  2. SR-5858

Incorrectly implementing LocalizedError protocols does not result in an error at compile time but an incorrect error localized description

    XMLWordPrintable

    Details

    • Type: Bug
    • Status: Resolved
    • Priority: Medium
    • Resolution: Done
    • Component/s: Compiler, Foundation
    • Labels:
    • Environment:

      Reproducable everywhere I have tried:

      Stable Xcode 8.3
      Latests Xcode 9 beta 6
      Swift Dev. 4.0 (Sep 5, 2017) Platform: Linux (x86_64)

      Description

      As in the summary, incorrectly implementing LocalizedError protocol leads to an incorrect localizedDescription string. Instead of an incorrect "The operation couldn’t be completed" when I call localizedDescription I would expect the compiler to complain because my implementation is incorrect.

      See below two implementations:

      import Foundation
      
      // This is the bad error.
      enum BadError: LocalizedError {
          case myFailure
          // Note the return type is not Optional<String> but String (Due to a typo, bad copy-pasting, whatever)
          var errorDescription: String {
              switch self {
              case .myFailure: return "BadErrorMyFailure"
              }
          }
      }
      
      // This is the good error
      enum GoodError: LocalizedError {
          case myFailure
          var errorDescription: String? {
              switch self {
              case .myFailure: return "GoodErrorMyFailure"
              }
          }
      }
      
      // No compiler error nothing. This compiles without problem in Swift3 and latest 4 too 
      print(BadError.myFailure.localizedDescription)
      // "The operation couldn’t be completed. (__lldb_expr_32.BadError error 0.)"
      // I expect a error at compile time since `errorDescription:String? { get }` is expected but I am writing `errorDescription:String { get }` (without the question mark)
      
      print(GoodError.myFailure.localizedDescription)
      // "GoodErrorMyFailure"
      

      Same example in swift sandbox

        Attachments

          Issue Links

            Activity

              People

              • Assignee:
                Unassigned
                Reporter:
                nacho4d Guillermo Ignacio Enriquez Gutierrez
              • Votes:
                0 Vote for this issue
                Watchers:
                3 Start watching this issue

                Dates

                • Created:
                  Updated:
                  Resolved: