1

I am not sure if this is new to Swift, but previously if I created a variable like this and then assigned it a value then I was able to get its value without unwrapping it:

var number: Int!
number = 10
print(number) // "10"

However now, instead of getting "10", I get "some(10)", and to get the value I need to unwrap it:

print(number!) // "10"

But if I need to unwrap its value then how's it different from using a normal optional variable with the question mark?

Marton Zeisler
  • 199
  • 3
  • 15
  • 1
    In short, an *implicitly unwrapped optional* will only be unwrapped if it is used in a situation that requires the unwrapped type. `print(number)` doesn't require an `Int`, so `number` will not be unwrapped. `let sum = 3 + number` does require an `Int`, so `number` will be unwrapped. – vacawama May 06 '18 at 11:29
  • Technically, doing `let string: String!; string = "foo"; label.text = string` would also require the unwrapped type; yet, the label will say `Optional("foo")`. Where's the logic behind that? I find this super confusing. It's like Andreas says [below the answer](https://stackoverflow.com/a/39537558/3397217) you've linked to, @vacawama. – LinusGeffarth May 06 '18 at 11:36
  • 1
    @LinusGeffarth why would that require unwrapping? `UILabel.text` is an optional property, so the compiler can simply assign the wrapped optional value to it, there's no need for unwrapping. – Dávid Pásztor May 06 '18 at 11:39
  • Yes, but the label on the screen will say `Optional("foo")` – LinusGeffarth May 06 '18 at 11:40
  • @LinusGeffarth, I just tried this and the label on the screen said `foo`. It didn't matter whether I declared `string` as `String?` or as `String!`. Doing `label.text = string` resulted in just `foo` on the screen. – vacawama May 06 '18 at 12:06
  • Can't reproduce it now, I just remembered that case. Maybe the `Optional` part came in somewhere else... – LinusGeffarth May 06 '18 at 12:07

0 Answers0