如何在 Swift 中创建一个空数组? [英] How to create an empty array in Swift?

查看:38
本文介绍了如何在 Swift 中创建一个空数组?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我真的对我们在 Swift 中创建数组的方式感到困惑.你能告诉我有多少种方法可以创建一个带有一些细节的空数组吗?

I'm really confused with the ways we create an array in Swift. Could you please tell me how many ways to create an empty array with some detail?

推荐答案

给你:

var yourArray = [String]()

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

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

增加价值

我想你最终会想要给它添加一个值!

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.remove(at: 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.index(of: "RemoveMe") {
    yourOtherArray.remove(at: indexValue)
}

这应该会让你开始!

这篇关于如何在 Swift 中创建一个空数组?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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