Skip to content

[SR-10931] Optional initialization inconsistent between Optional<T> vs T? #53322

Open
@masters3d

Description

@masters3d
Previous ID SR-10931
Radar None
Original Reporter @masters3d
Type Bug
Environment

swift 5.0

Additional Detail from JIRA
Votes 2
Component/s Compiler
Labels Bug
Assignee None
Priority Medium

md5: 0e6cd4419cd22cf69c97288a90ec7e94

relates to:

  • SR-354 Non-optional variable tuple of optional values should not have default value
  • SR-801 TestPOUnwrapping.py - PO for optional class members set to nil are showing up as if 0 or ""
  • SR-11768 Stored property declaration + initialization expressions cannot be inlinable
  • SR-11777 'var something: 'Type?' always get double initialised

Issue Description:

I am having a hard time understanding why T? variables auto initialize to nil when Optional<T> variables do not. This seems like a bug to me. If it's not a bug, where else is this feature being used?

do{ 
let someValue1:Optional<String> 
//print(someValue1) // error: constant 'someValue1' used before being initialized 
var someValue11:Optional<String> 
// print(someValue11) // error: variable 'someValue11' used before being initialized 
let someValue2:String? 
// print(someValue2) //error: constant 'someValue2' used before being initialized 
var someValue22:String? 
print(someValue22) // Compiler happy. Why? What is the technical reason why this should work. 

// Now consider the following type of optional. 
var someValue33:String!
print(someValue33 + "") // Boom Crash. Implicit initialization here is actually dangerous. 
}

Metadata

Metadata

Assignees

No one assigned

    Labels

    OptionalArea → standard library: The `Optional` typebugA deviation from expected or documented behavior. Also: expected but undesirable behavior.compilerThe Swift compiler itselfdefault initializationFeature: Default initialization of variablesswift 6.1type checkerArea → compiler: Semantic analysisunexpected errorBug: Unexpected error

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions