首页 > 解决方案 > var数组和let数组的区别?

问题描述

我正在研究 Swift 中的数组,在我的书中他们首先写道:

let numbers = [0, 1, 2, 3]

但然后写:

var numbers = [0, 1, 2, 3]

我知道它let表示常量var引用变量,但实际上声明为常量的数组和声明为变量的数组有什么变化?

标签: arraysswiftxcodevarlet

解决方案


因为 swift 中structs的数组声明了一个数组,let它不仅会阻止您为其分配新值,还会阻止您更改其内容

例如:

    let arr = [0, 1, 2]
    arr[0] = 10 //will not compile
    arr = [] //will not compile

推荐阅读