2

In js I can freeze an array after adding some elements to an array. Is there anything to freeze an array in Swift?

What is freezing?

Ans: Suppose we have an array. We add some elements to that array.

/* This is javascript code */
var fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.push("Kiwi");
// fruits contains some elements

// Now freeze fruits. After freezing, no one can add, delete, modify this array.
Object.freeze(fruits);

My question is here - "Is there anything in swift where we can freeze an array?"

Bhavik Modi
  • 1,517
  • 14
  • 29
Faruk Hossain
  • 1,205
  • 5
  • 12

1 Answers1

6

You can create an immutable copy of the array, but the mutability of objects is only controlled by the variable declaration (let for immutable and var for mutable), so once you create a mutable object, you cannot make it immutable or vice-versa.

var fruits = ["Banana", "Orange", "Apple", "Mango"]
fruits.append("Kiwi")

let finalFruits = fruits // Immutable copy
finalFruits.append("Pear") // Gives compile-time error: Cannot use mutating member on immutable value: 'finalFruits' is a 'let' constant
Dávid Pásztor
  • 51,403
  • 9
  • 85
  • 116