-1

Well I understand the concept of optionals and the nil value and how swift wants to keep your code safe from errors

Swift is great at inferring variables. But why doesn't the swift compiler accept just a declared variable.

That's to say, Why would

let unInitializedVariable: Int

throw an error or not allowed yet if I say

let unInitializedVariable: Int? = nil

then the compiler is happy. Would It be meaningless If say the compiler inferred the first statement to be the same as the later expression? Can someone please explain.

  • You need to set `unInitializedVariable` later in your code. Check this https://stackoverflow.com/a/47585714/2303865 – Leo Dabus Apr 03 '20 at 21:58

1 Answers1

0

It's not that the compiler can't infer it. It doesn't want to. Type safety means you get the type you want.

Int? and Int are very different. Int means you have a value, Int? means you may or may not have a value.

With JSONDecoder, if you have a struct with an Int in there, you will get an error if its key and value are missing. If it is an Int? it doesn't care if it is there or not. Int and Int? look the same, but they work very differently.

HalR
  • 11,411
  • 5
  • 48
  • 80