解釋 let 和 var

Asked on 03/06/2025

1 search

In Swift, the keywords let and var are used to declare constants and variables, respectively.

  • let: This keyword is used to declare a constant. Once a constant is assigned a value, it cannot be changed. This immutability helps in making the code easier to reason about and prevents accidental changes to values that should remain constant. For example, if you declare a variable with let, Swift guarantees that the value will not change.

  • var: This keyword is used to declare a variable that can be changed after it is initialized. Variables declared with var are mutable, meaning you can assign a new value to them at any point in their lifecycle.

For more details, you can refer to the session A Swift Tour: Explore Swift’s features and design (02:35) where these concepts are discussed.