0

I have a Struct:

struct Note{
    var date: String;
    var comment: String;
}

Then I create a an array with two arrays nested within,

var data = [[Note()],[Contributors()]]

These two arrays are used to populate two sections of a Table View. I need to append a struct onto the Notes struct array but when I try and append it using

data[0].append(Note(date: "06-06-2012",comment:"Created Note"))

and

(data[0] as! Note).append(Note(date: "06-06-2012",comment:"Created Note"))

throws the error

Cannot use mutating member on immutable value of type 'Note'

How you can mutate values that need to be casted?

1
  • You need to append not a new Note AND Contributors (based on my testing) - data.append([Note(data: "06-06-2012",comment:"Created Note"), [Contributors()]] or something like that Commented May 21, 2018 at 1:02

2 Answers 2

1

Your initial creation of the arrays is incorrect.

Change:

var data = [[Note()],[Contributors()]]

to:

var data: [Any] = [[Note](),[Contributors]()]

Your code creates an array that contains at index 0 an array of Any that contains one empty Note instance and at index 1 an array of Any that contains one empty Contributors instance.

The fix creates an array that contains an empty Note array at index 0 and an empty Contributors array at index 1.

But even with all of those "fixes", you still get the error if you do:

(data[0] as! Note).append(Note(date: "06-06-2012",comment:"Created Note"))

It's kind of strange to have data contain two different types of data. You really should have two arrays:

var notes = [Note]()
var contributors = [Contributors]()

Then you can easily do:

notes.append(Note(date: "06-06-2012",comment:"Created Note"))
Sign up to request clarification or add additional context in comments.

Comments

0

You can have solution by using protocol

protocol DataSourceNoteContributors {}

struct Contributors: DataSourceNoteContributors{

}
struct Note:DataSourceNoteContributors{
    var date: String;
    var comment: String;
}

Then can be used easly

    var data = [Note(date: "date", comment: "comment"),Contributors()]

    data.append(Note(date: "note1", comment: "comment2"))
    data.append(Contributors())

// using cast to recognize

if data[0] as Note {

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.