What is the use of creating a Constray (let) object with an empty Array?

In the Swift PDF file released by Apple I have studied this code thoroughly

Use initializer syntax to create an empty array or dictionary.

let emptyArray = [String]()
let emptyDictionary = [String: Float]()

      

This is using the creation of a let (constant) object with an empty array, where we cannot insert any values ​​into it in the next line ?? !!

+3


source to share


3 answers


Not much use, but the value can be copied:



let emptyDictionary = [String: Float]()
var otherDictionary = emptyDictionary
otherDictionary["a"] = 0.5

      

0


source


when teaching the lens, they start to learn how

NSArray *arrayObj = [[NSArray alloc] init] 

      

if we declare like this we cannot add objects after initialization
similarly they teach us how to initialize an array or dictionary objects



Another difference is that we allocate an empty array, then we can assign another array with that.

let will prevent you from assigning another array to it.

let emptyArray = [String]()
let/var filledArray = ["stack", "overflow"]

emptyArray = filledArray  //  will give you an error 

      

+4


source


The property declaration sets them by default, but you can actually change the value to something else in init. This will only be the case for class properties and not for built-in properties.

Here's a class-scoped example where a let property may have a default but needs to be changed:

class Whatever {

    let testArray = [Int]()

    init() {
        testArray = [0,1,2]
    }
}

      

0


source







All Articles