Swift - Append to array in struct

本小妞迷上赌 提交于 2019-12-14 02:19:54

问题


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:


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



来源:https://stackoverflow.com/questions/31373400/swift-append-to-array-in-struct

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!