Differences Objective-C const and let Swift in terms of run and compile time

Viewed 266

I am trying to figure out difference between Objective-C and Swift constant. I just read a tutorial document

//Objective-C
const int number = 0;
//Swift
let number = 0

"A const is a variable initialized at compile time with a value or an expression that must be resolved at compilation time. An immutable created with let is a constant determined at runtime. You can initialize it with a static or a dynamic expression. This allows a declaration such as:

let higherNumber = number + 5

Note that you can only assign its value once."

Can someone explain these phrases and deep little dive into to explain why let constant determined at runtime ? I was thinking let is constant and never change.

1 Answers

Let means once assigned the value can’t be changed. The compiler will enforce that. An expression like “let now=Date()” can’t be determined at compile time but at compile time you can disallow reassigning to “now”.. “let pi = 3.141” can be determined at compile time, enabling optimisations and that is like C’s const

Note for reference types (classes) let means the assigned object will continue to be the same object, it doesn’t mean the object itself can’t or doesn’t change.

Related