【发布时间】:2015-10-01 03:05:48
【问题描述】:
我目前正在学习 swift 并正在试验数据结构。在可能的代码中,我有某些带有名称(字符串)和几个任务(字符串数组)的例程。这些值在一个结构中。
所以我试图在初始化后向数组添加另一个值。我的代码实际上正在运行,但是我真的认为它非常奇怪和奇怪,并且不要认为这是应该完成的方式。
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);
}
}
我尝试了一些(对我而言)“更正确”的方法,例如:
routines[0].tasks.append("Salut");
但我总是遇到很多错误,我也不明白。
所以我现在的问题是:它实际上是如何正确完成的?为什么第二种方法不起作用?
非常感谢您的帮助和建议!
【问题讨论】:
标签: arrays swift struct append