且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何在Swift中创建一个空数组?

更新时间:2023-11-18 20:20:34

你走了:

var yourArray = [String]()

以上也适用于其他类型,而不仅仅是字符串。这只是一个例子。

The above also works for other types and not just strings. It's just an example.

为其添加值

我认为你' ll最终想要为它添加一个值!

I presume you'll eventually want to add a value to it!

yourArray.append("String Value")

let someString = "You can also pass a string variable, like this!"
yourArray.append(someString)

通过插入添加

一旦有了几个值,就可以插入新值而不是附加值。例如,如果要在数组的开头插入新对象(而不是将它们附加到结尾):

Once you have a few values, you can insert new values instead of appending. For example, if you wanted to insert new objects at the beginning of the array (instead of appending them to the end):

yourArray.insert("Hey, I'm first!", atIndex: 0)

或者你可以使用变量使你的插入更灵活:

Or you can use variables to make your insert more flexible:

let lineCutter = "I'm going to be first soon."
let positionToInsertAt = 0
yourArray.insert(lineCutter, atIndex: positionToInsertAt)

你可能最终要删除一些东西

var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.removeAtIndex(1)

以上情况很有用你知道数组在数组中的位置(也就是说,当你知道它的索引值时)。当索引值从0开始时,第二个条目将在索引1处。

The above works great when you know where in the array the value is (that is, when you know its index value). As the index values begin at 0, the second entry will be at index 1.

在不知道索引的情况下删除值

但是如果你不这样做呢?如果yourOtherArray有数百个值并且您知道要删除等于RemoveMe的那个怎么办?

But what if you don't? What if yourOtherArray has hundreds of values and all you know is you want to remove the one equal to "RemoveMe"?

if let indexValue = yourOtherArray.indexOf("RemoveMe") {
    yourOtherArray.removeAtIndex(indexValue)
}

这应该可以帮到你!