Reputation: 91
If I want to make a variable an optional, I can do:
var exampleString: String? = nil
or
var exampleString: String? = "This is a string"
Is it possible to declare an optional value without assigning a type like String, Int, Bool, etc?
Something like (that doesn't return an error):
var exampleVar? = nil
I have no use case for why I want to do this, but I'm trying to better understand optionals. I just read through the Optionals section in Swift docs. If this can be done, would there be any advantage to doing this?
Also, why would I not want to use implicitly unwrapped optionals everywhere? What would be the disadvantages of this? Apple's Swift docs mentions that you shouldn't do this if you intend to reassign a variable to nil. Why?
Thanks so much for your help guys!
Upvotes: 1
Views: 309
Reputation: 135540
Is it possible to declare an optional value without assigning a type like String, Int, Bool, etc?
No. The reason is that Optional
(without its generic parameter) is not a complete type — think of it as a type constructor, i.e. a way to produce a full type if you give it the missing information.
The compiler needs to know the full type — Optional<Int>
or Optional<String>
and so on — to allocate the right amount of memory etc. An Optional<String>
will take up more memory than an Optional<Bool>
, even if both are nil
.
The same is true for other generic types like Array
. Array
is the type constructor, Array<Int>
the complete type.
Edit: rmaddy makes a good point: var exampleVar: Any? = nil
allows you to store any value in this optional. Note that we're still dealing with a full type here — Optional<Any>
. It's just that all types are compatible with Any
. In that sense, Optional<Any>
is not much different from Optional<SomeProtocol>
, which can store any value that conforms to the SomeProtocol
protocol.
Upvotes: 5