How exactly does the “let” keyword work in Swift?

后端 未结 6 854
时光说笑
时光说笑 2020-12-02 23:27

I\'ve read this simple explanation in the guide:

The value of a constant doesn’t need to be known at compile time, but you must assign it a value exa

6条回答
  •  星月不相逢
    2020-12-02 23:59

    let is a little bit like a const pointer in C. If you reference an object with a let, you can change the object's properties or call methods on it, but you cannot assign a different object to that identifier.

    let also has implications for collections and non-object types. If you reference a struct with a let, you cannot change its properties or call any of its mutating func methods.

    Using let/var with collections works much like mutable/immutable Foundation collections: If you assign an array to a let, you can't change its contents. If you reference a dictionary with let, you can't add/remove key/value pairs or assign a new value for a key — it's truly immutable. If you want to assign to subscripts in, append to, or otherwise mutate an array or dictionary, you must declare it with var.

    (Prior to Xcode 6 beta 3, Swift arrays had a weird mix of value and reference semantics, and were partially mutable when assigned to a let -- that's gone now.)

提交回复
热议问题