Consider the following Swift code:
let numbers = [1, 2, 3] numbers.append(4) print(numbers)
What will happen when this code runs?
let numbers = [1, 2, 3] numbers.append(4) print(numbers)
Think about whether let allows changing the array.
In Swift, arrays declared with let are immutable. You cannot add elements to them. Trying to call append causes a compile-time error.
Consider this Swift code:
var fruits = ["apple", "banana"]
fruits.append("cherry")
print(fruits)What will be printed?
var fruits = ["apple", "banana"] fruits.append("cherry") print(fruits)
Think about whether var allows changing the array.
Arrays declared with var are mutable. You can add elements using append. So the array will include "cherry".
Given the following Swift code snippets, which one will cause a compile-time error?
Check which dictionary is declared with let and then mutated.
Dictionaries declared with let are immutable. Trying to add or change keys causes a compile-time error.
Examine this Swift code:
let set: Set= [1, 2, 3] set.insert(4) print(set)
Why does it fail to compile?
let set: Set<Int> = [1, 2, 3] set.insert(4) print(set)
Think about whether let allows changing the set.
Sets declared with let are immutable. You cannot add elements to them. Calling insert causes a compile-time error.
Which statement best describes how Swift handles mutability of collections declared with let and var?
Think about the difference between let and var in Swift.
In Swift, let makes a collection immutable, so you cannot change its contents. var allows modification of the collection's contents.