Skip to content

[SR-9516] Assigning an implicity unwrapped optional should unwrap it #51968

@swift-ci

Description

@swift-ci
Previous ID SR-9516
Radar None
Original Reporter jalkut@red-sweater.com (JIRA User)
Type Bug
Additional Detail from JIRA
Votes 0
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: ea6b3507dbe39e8fbf87a0bf6925e4a4

Issue Description:

When working with an implicitly unwrapped optional, I think that assigning the value to another variable should either unwrap the optional, or perpetuate the compiler's understanding of the optional as being implicitly unwrapped.

When working with an implicitly unwrapped optional, it's common to treat it as effectively non-optional. Here's a contrived scenario where a random value is chosen from between two derived values: one an IUO, and the other non-optional:

func takesAnInt(theInt: Int) { print("Got \(theInt)") }

let neverNil: Int! = 3
let alsoNeverNil = 5

let randomNeverNil = Int.random(in: 0...1) == 0 ? neverNil : alsoNeverNil

// Error: randomNeverNil not unwrapped
takesAnInt(theInt: randomNeverNil)

In this kind of scenario, care should not need to be taken to either additionally check for nil, or force-unwrap randomNeverNil. In my opinion the contract for an IUO is that it will be unwrapped when used, and that assigning it to another variable is as good an example of using it as passing it as a value to a function.

The practical scenario I run into this most is with IBOutlets that are IUO. I am liable to assign the property value to a local variable inside a function, only to be forced to unwrap it before passing it to another method.

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