Swift - 附加到结构中的数组 [英] Swift - Append to array in struct

查看:26
本文介绍了Swift - 附加到结构中的数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在快速学习并且正在试验数据结构.在可能的代码中,我有一些带有名称(字符串)和几个任务(字符串数组)的例程.这些值在一个结构中.

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!

推荐答案

您可以创建一个函数来附加结构中的值(这就是我要做的).您甚至可以使用它来验证值或附加之前您需要执行的任何其他操作,它还可以返回一个布尔值让您的代码知道该值是否已成功附加

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")
    }  
}

希望能帮到你

这篇关于Swift - 附加到结构中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆