Swift - Append to array in struct

2019-07-09 05:08发布

I am currently learning swift and am experimenting with data structures. In may code I have certain routines with a name(String) and several tasks(Array of Strings). These values are in a structure.

So I am trying to add another value to the array after it has been initialized. My code is actually working, however I really think it very weird and odd and DO NOT think, that it is the way it should be done.

var routineMgr: routineManager = routineManager();
struct routine{
    var name = "Name";
    var tasks = [String]();
}

class routineManager: NSObject {
var routines = [routine]();

func addTask(name: String, desc: String){
    //init routines with name and an array with certain values, here "Hallo" & "Moin"
    routines.append(routine(name: name, tasks: ["Hallo","Moin"]));

 //so i just put this part here to make the example shorter, but it would be in ad different function to make more sense

    //adding a new value ("Salut") to the tasks array in the first routine
    //getting current array
    var tempArray = routines[0].tasks;
    //appending new value to current value
    tempArray.append("Salut");
    //replacing old routine with a copy (same name), but the new array (with the appended salut)
    routines[0] = routine(name: routines[0].name, tasks: tempArray);
}  
}

I have tried some (to me) "more correct" ways, like:

routines[0].tasks.append("Salut");

But I always got tons of errors, which I also did not understand.

So my question now: How is it actually done correctly? And why does the second way not work?

Your help and advice is really appreciated!

1条回答
萌系小妹纸
2楼-- · 2019-07-09 05:49

You can create a function to append the values in the struct (that is what I would do). You can even use it to validade values or anything else you need to do before append, it can also return a boolean to let your code know if the value was successfully appended or not

var routineMgr: routineManager = routineManager();
struct routine{
    var name = "Name";
    var tasks = [String]();

    mutating func addTask(task: String){
        tasks.append(task)
    }
}

class routineManager: NSObject {
var routines = [routine]();

    func addTask(name: String, desc: String){
        routines.append(routine(name: name, tasks: ["Hallo","Moin"]));
        routines[0].addTask("Salut")
    }  
}

I hope that helps

查看更多
登录 后发表回答