如何在struct数组中插入数字(Swift4)

时间:2022-09-06 11:23:13

My code is not working. All I am trying to do is get the number inserted into the struct's internal array. Right now this is not working:

我的代码不起作用。我想要做的就是将数字插入到struct的内部数组中。现在这不起作用:

@IBAction func move(_ sender: Any) {
    bad.numbers.insert(0, at: 0)
}


struct bad {
    var numbers: [Int] = [1, 2, 3]
}

1 个解决方案

#1


3  

You need to declare your numbers property as static. Btw it is Swift convention to name your structures starting with an uppercase letter:

您需要将您的数字属性声明为静态。顺便说一句,Swift惯例是以大写字母开头命名结构:

struct Bad {
    static var numbers: [Int] = [1, 2, 3]
}

And to insert elements at index 0, you need to call it like this :

要在索引0处插入元素,您需要像这样调用它:

Bad.numbers.insert(0, at: 0)

print(Bad.numbers)  // "[0, 1, 2, 3]\n"

#1


3  

You need to declare your numbers property as static. Btw it is Swift convention to name your structures starting with an uppercase letter:

您需要将您的数字属性声明为静态。顺便说一句,Swift惯例是以大写字母开头命名结构:

struct Bad {
    static var numbers: [Int] = [1, 2, 3]
}

And to insert elements at index 0, you need to call it like this :

要在索引0处插入元素,您需要像这样调用它:

Bad.numbers.insert(0, at: 0)

print(Bad.numbers)  // "[0, 1, 2, 3]\n"