Reputation: 41480
When will a variable be inferred as an implicitly unwrapped optional by Swift compiler? Or the variable has to always be declared with ! for it to be treated as such?
Upvotes: 2
Views: 218
Reputation: 76918
The type inference occurs at compile time. The only way for a variable to be inferred as an implicitly unwrapped optional is to assign one to it (either directly, or by assigning the return value of a function, which returns an implicitly unwrapped optional).
Basically, the "optional-ness" of a variable is part of it's type. The type of the following variables, x
and y
is implicitly unwrapped Optional Int
(for both), and most importantly, the type system does not consider this the "same type" as Int
. (Though you can use it interchangeably with an Int
as long as it is not nil
)
let x: Int! = 7
fund make_y() -> Int! {
return 7
}
let y = make_y()
Upvotes: 1