Understanding difference in Swift properties for structs and classes in assignment

57 views Asked by At

My question is in regards to an error that I kept on seeing while writing a function to initialize an optional array in a struct that I solved by just changing the struct to the class. I am hoping that someone can explain to me what I am not understanding about structs and classes that is causing this problem. Here is my code.

struct DataStorage {
//When I change this to class DataStorage this works
    var listOfVariables = [VariableType]
    var allDataPoints: [[DataPoint]]?
    init() {
        listOfVariables = VariableType.getAllVariables(managedObjectContext)
    }
    func initializeAllDataPoints() {
        //THIS IS THE LINE IN QUESTION
        allDataPoints = [[DataPoint]](count: listOfVariables.count, repeatedValue: [DataPoint]())
    }
}

So, the function initializeAllDataPoints is what is causing the error and that is truly the relevant part of this question. The error that I get is Cannot assign to 'allDataPoints' in 'self'. I only get this error when DataStorage is a struct and I don't get it when DataStorage is a class. What am I not understanding about classes and structs that is causing this difference in behavior?

1

There are 1 answers

0
Aaron Rasmussen On BEST ANSWER

Whenever a method in a struct modifies one of its own properties, you have to use the mutating keyword.

I believe that if you write:

mutating func intializeAllDataPoints() { ... }

it should work for you.

This article gives a little more background information.