Skip to content

[SR-5858] Incorrectly implementing LocalizedError protocols does not result in an error at compile time but an incorrect error localized description #4069

@swift-ci

Description

@swift-ci
Previous ID SR-5858
Radar rdar://problem/41721949
Original Reporter nacho4d (JIRA User)
Type Bug
Status Resolved
Resolution Done

Attachment: Download

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)

Additional Detail from JIRA
Votes 0
Component/s Compiler, Foundation
Labels Bug, TypeChecker
Assignee None
Priority Medium

md5: b7f836ae6e1516ca27059acef1da0130

relates to:

  • SR-522 Protocol funcs cannot have covariant returns

Issue 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

Metadata

Metadata

Assignees

No one assigned

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions