Easy - trying to create new class object in new projects results in 6 errors

I have this "error" reproduced in new project. The only thing that I edit is contentview. I know it must be something easy, but I followed swift docs pretty verbatim and I think this kind of object creation should work.

Here is what I changed in new project

struct ContentView: View {
    class Note {
        var antecedent = ""
        var behavior = ""
        var consequence = ""
        var datetime: Date = Date.init()
    var testNote = Note()
    testNote.antecedent = "Hello World"
    var body: some View {
        Text("Hello, World!")

And I get 6 errors:
Consecutive declarations on a line must be separated by ';'
Insert ';'
Expected '(' in argument list of function declaration
Expected '{' in body of function declaration
Expected 'func' keyword in instance method declaration
Insert 'func '
Expected declaration
Invalid redeclaration of 'testNote()'

This shouldn’t be there. You can’t do assignments like this in a struct/class scope.

so how do I create new object and set values for this object?

There are multiple ways.

You can give Note a dedicated initializer and pass through antecedent directly when you initialize. (Because Note is a class, you do not get automatically generated initializers for free):

struct ContentView: View {
    class Note {
        var antecedent: String
        var behavior: String
        var consequence: String
        var datetime: Date

        init(antecedent: String = "", behavior: String = "", consequence: String = "", datetime: Date = Date()) {
           self.antecedent = antecedent
           self.behavior = behavior
           self.consequence = consequence
           self.datetime = datetime
    var testNote = Note(antecedent: "Hello World")

Or set the value when initializing ContentView:

struct ContentView: View {
    class Note { /* etc */ }
    var testNote: Note

    init() {
        testNote = Note()
        testNote.antecedent = "Hello World"
1 Like

thank you so much!