回复: [Design Question] Unexpected forced optional unwrapping behavior


(Yang Wu) #1

Shouldn’t type associate on reference instead of its value?

I agree its syntax is a little suprise : dereferencing an optional without value doesn’t throw an error.

I’ve spent some time exploring different aspects of the language’s type system and came across a case where I wanted to know the type of the thing an optional might hold, if it exists. The direct type of an optional variable is, unsurprisingly, an optional:

var example: String? = “example”

example: String? = “example”

example.dynamicType

$R1: String?.Type = String?

Ok, that didn’t work. What if I dereference?

example!.dynamicType

$R2: String.Type = String

Ok. What if the optional doesn’t currently have a value? Does this still work?

example = nil

$R3: String.Type = String

That’s odd. I expected it not work, given how forced unwrapping of nil optionals usually turns out.

Is this explicitly intended behavior, something that really shouldn’t work and shouldn’t be relied on, or… other?

Mike

主题:[swift-evolution] [Design Question] Unexpected forced optional unwrapping behavior
发件人:Michael Henson via swift-evolution
收件人:swift-evolution
抄送:

···

-------- 原始邮件 --------