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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/30430550/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 06:04:13  来源:igfitidea点击:

How to create an empty array in Swift?

iosarraysswift

提问by Inuyasha

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?

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

回答by Dave G

Here you go:

干得好:

var yourArray = [String]()

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

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

Adding Values to It

为它增加价值

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

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

yourArray.append("String Value")

Or

或者

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

Add by Inserting

通过插入添加

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)

You May Eventually Want to Remove Some Stuff

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

var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"]
yourOtherArray.remove(at: 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.

当您知道该值在数组中的位置时(即,当您知道它的索引值时),上述方法非常有效。由于索引值从 0 开始,第二个条目将位于索引 1。

Removing Values Without Knowing the Index

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

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"?

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

if let indexValue = yourOtherArray.index(of: "RemoveMe") {
    yourOtherArray.remove(at: indexValue)
}

This should get you started!

这应该让你开始!

回答by vichhai

var myArr1 = [AnyObject]()

can store any object

可以存储任何对象

var myArr2 = [String]()

can store only string

只能存储字符串

回答by DPen

You could use

你可以用

var firstNames: [String] = []

回答by Lorem Ipsum Dolor

Swift 3

斯威夫特 3

There are three (3) ways to create a empty array in Swift and shorthand syntaxway is always preferred.

在 Swift 中有三 (3) 种方法可以创建空数组,并且始终首选速记语法方式。

Method 1: Shorthand Syntax

方法 1:速记语法

var arr = [Int]()

Method 2: Array Initializer

方法 2:数组初始值设定项

var arr = Array<Int>()

Method 3: Array with an Array Literal

方法 3:带有数组字面量的数组

var arr:[Int] = []

Method 4: Credit goes to @BallpointBen

方法 4:归功于@BallpointBen

var arr:Array<Int> = []

回答by Aaron

There are 2 major ways to create/intialize an array in swift.

有两种主要方法可以快速创建/初始化数组。

var myArray = [Double]()

This would create an array of Doubles.

这将创建一个双打数组。

var myDoubles = [Double](count: 5, repeatedValue: 2.0)

This would create an array of 5 doubles, all initialized with the value of 2.0.

这将创建一个包含 5 个双精度值的数组,所有数组都使用 2.0 的值进行初始化。

回答by piyush ranjan

If you want to declare an empty array of string type you can do that in 5 different way:-

如果你想声明一个字符串类型的空数组,你可以用 5 种不同的方式来做到这一点:-

var myArray: Array<String> = Array()
var myArray = [String]()
var myArray: [String] = []
var myArray = Array<String>()
var myArray:Array<String> = []

Array of any type :-

任何类型的数组:-

    var myArray: Array<AnyObject> = Array()
    var myArray = [AnyObject]()
    var myArray: [AnyObject] = []
    var myArray = Array<AnyObject>()
    var myArray:Array<AnyObject> = []

Array of Integer type :-

整数类型数组:-

    var myArray: Array<Int> = Array()
    var myArray = [Int]()
    var myArray: [Int] = []
    var myArray = Array<Int>()
    var myArray:Array<Int> = []

回答by Bobby

Here are some common tasks in Swift 4 you can use as a reference until you get used to things.

以下是 Swift 4 中的一些常见任务,您可以将其用作参考,直到您习惯了为止。

    let emptyArray = [String]()
    let emptyDouble: [Double] = []

    let preLoadArray = Array(repeating: 0, count: 10) // initializes array with 10 default values of the number 0

    let arrayMix = [1, "two", 3] as [Any]
    var arrayNum = [1, 2, 3]
    var array = ["1", "two", "3"]
    array[1] = "2"
    array.append("4")
    array += ["5", "6"]
    array.insert("0", at: 0)
    array[0] = "Zero"
    array.insert(contentsOf: ["-3", "-2", "-1"], at: 0)
    array.remove(at: 0)
    array.removeLast()
    array = ["Replaces all indexes with this"]
    array.removeAll()

    for item in arrayMix {
        print(item)
    }

    for (index, element) in array.enumerated() {
        print(index)
        print(element)
    }

    for (index, _) in arrayNum.enumerated().reversed() {
        arrayNum.remove(at: index)
    }

    let words = "these words will be objects in an array".components(separatedBy: " ")
    print(words[1])

    var names = ["Jemima", "Peter", "David", "Kelly", "Isabella", "Adam"]
    names.sort() // sorts names in alphabetical order

    let nums = [1, 1234, 12, 123, 0, 999]
    print(nums.sorted()) // sorts numbers from lowest to highest

回答by ABS

Array in swift is written as **Array < Element > **, where Element is the type of values the array is allowed to store.

swift 中的数组写为 **Array < Element > **,其中 Element 是数组允许存储的值的类型。

Array can be initialized as :

数组可以初始化为:

let emptyArray = [String]()

let emptyArray = [String]()

It shows that its an array of type string

它表明它是一个字符串类型的数组

The type of the emptyArray variable is inferred to be [String] from the type of the initializer.

根据初始值设定项的类型推断 emptyArray 变量的类型为 [String]。

For Creating the array of type string with elements

用于创建带有元素的字符串类型数组

var groceryList: [String] = ["Eggs", "Milk"]

var groceryList: [String] = ["Eggs", "Milk"]

groceryList has been initialized with two items

杂货清单已初始化为两个项目

The groceryList variable is declared as “an array of string values”, written as [String]. This particular array has specified a value type of String, it is allowed to store String values only.

杂货清单变量被声明为“字符串值数组”,写为 [String]。这个特定的数组指定了一个字符串值类型,它只允许存储字符串值。

There are various properities of array like :

数组有各种属性,例如:

- To check if array has elements (If array is empty or not)

- 检查数组是否有元素(如果数组为空)

isEmpty property( Boolean ) for checking whether the count property is equal to 0:

isEmpty 属性( Boolean ) 用于检查 count 属性是否等于 0:

if groceryList.isEmpty {
    print("The groceryList list is empty.")
} else {
    print("The groceryList is not empty.")
}

- Appending(adding) elements in array

- 在数组中追加(添加)元素

You can add a new item to the end of an array by calling the array's append(_:) method:

您可以通过调用数组的 append(_:) 方法将新项添加到数组的末尾:

groceryList.append("Flour")

groceryList now contains 3 items.

杂货清单现在包含 3 个项目。

Alternatively, append an array of one or more compatible items with the addition assignment operator (+=):

或者,使用加法赋值运算符 (+=) 附加一个或多个兼容项的数组:

groceryList += ["Baking Powder"]

groceryList now contains 4 items

杂货清单现在包含 4 个项目

groceryList += ["Chocolate Spread", "Cheese", "Peanut Butter"]

groceryList now contains 7 items

杂货清单现在包含 7 个项目

回答by Ullas Kumar

you can remove the array content with passing the array index or you can remove all

您可以通过传递数组索引来删除数组内容,也可以删除所有内容

    var array = [String]()
    print(array)
    array.append("MY NAME")
    print(array)
    array.removeFirst()
    print(array)
    array.append("MY NAME")
    array.removeLast()
    array.append("MY NAME1")
    array.append("MY NAME2")
    print(array)
    array.removeAll()
    print(array)

回答by Manoj Perumarath

As per Swift 5

根据 Swift 5

    // An array of 'Int' elements
    let oddNumbers = [1, 3, 5, 7, 9, 11, 13, 15]

    // An array of 'String' elements
    let streets = ["Albemarle", "Brandywine", "Chesapeake"]

    // Shortened forms are preferred
    var emptyDoubles: [Double] = []

    // The full type name is also allowed
    var emptyFloats: Array<Float> = Array()