简体   繁体   中英

swift declare a constant without let

In Swift programming language we can declare a constant like that :

 let sth = "something"

but I found that we can write

window = UIWindow(frame: UIScreen.mainScreen().bounds)

it doesn't use the keyword let, so what does that mean?

That means that you're modifying an existing instance property of a class. I'd guess you did this inside your app delegate or a UIView subclass.

Normally you must use either let or var , so if you're able to assign a value to window without one of those keywords it's because the scope you're in already has it declared.

 window = UIWindow(frame: UIScreen.mainScreen().bounds)

If you are trying to write this code then you must have declare a variable like this :

var window: UIWindow?

The let keyword is used to define constant. And Its value can not be change afterwords. Var is used to define variables.

You can give a try your above line of code without declaring a Variable. It will give you an error for sure.

Any declaration, whether it is a constant or a variable has to be made using the let (for constant) and var (for variable) keywords. For example

var window = UIWindow(frame: UIScreen.mainScreen().bounds)
let window2 = UIWindow(frame: UIScreen.mainScreen().bounds)

window is a variable because it is created using var and window2 is a constant because it is created using let . Now in the code below

window = UIWindow(frame: UIScreen.mainScreen().bounds)
window2 = UIWindow(frame: UIScreen.mainScreen().bounds)//error

line 1 will work properly but line 2 will give an error because you cannot re-assign a value to a constant.

You can try the above code in a playground and check the error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM