Swift - 追加到结构中的数组

Swift - Append to array in struct(Swift - 追加到结构中的数组)

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

问题描述

我目前正在学习 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 - 追加到结构中的数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!

本文标题为:Swift - 追加到结构中的数组

基础教程推荐