Skip to content

[SR-12662] Optional initializer for the .init() is not accepted #55106

@swift-ci

Description

@swift-ci
Previous ID SR-12662
Radar rdar://problem/62895055
Original Reporter mstana (JIRA User)
Type Bug
Status Resolved
Resolution Done
Additional Detail from JIRA
Votes 1
Component/s Compiler
Labels Bug
Assignee mstana (JIRA)
Priority Medium

md5: c976c9957f9cd93079042c559eebe65c

relates to:

  • SR-10569 Compiler is confused when both dot syntax and forced unwrapping are used.

Issue Description:

When an optional initializer is supposed to be used compiler is complaining about the non-optional type.

The test can be performed in the playground by copy-paste this code:

struct Foo {
    let title: String
    init?(_ dictionary: [String: Any]?) {
        guard
            let title = dictionary?["title"] as? String
        else {
            return nil
        }

        self.title = title
    }


    static var `default`: Self {
        Self(["title": "default"])!
    }
}

func getNonOptionalFoo() -> Foo {
    .init(["title": "new default"]) ?? .default
}

Compiler error:

Value of optional type 'Foo?' must be unwrapped to a value of type 'Foo'

Metadata

Metadata

Assignees

No one assigned

    Labels

    bugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itself

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions