Swift Variable Declaration and Initialize

2020-04-08 13:02发布

Is there a difference between how following bits of code work?

let x: Int = 4

and

let x: Int
x = 4

标签: swift
2条回答
我想做一个坏孩纸
2楼-- · 2020-04-08 13:19

This one:

let x: Int = 4

creates a non-optional variable x and initialises it to 4. x can be used without issue.

This one:

let x: Int
// Cannot do anything with x yet
x = 4

creates a non-optional variable x with no defined value. It cannot be used without first assigning it to a value, either directly (as in your example) or by the result of some other statement. If you do try and use it, you'll get a compile-time error.

查看更多
聊天终结者
3楼-- · 2020-04-08 13:26

The only difference is that on the first one you are declaring a variable and assigning it at the same time, and the second one you declare it first and then assign it.

But there is no mayor difference.

查看更多
登录 后发表回答