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

时间:2022-11-24 11:12:26

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中创建数组的方式。您能告诉我创建一个空数组有多少种方法吗?

9 个解决方案

#1


167  

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.removeAtIndex(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"?

但如果你没有呢?如果你的数组有数百个值,你只知道你想要移除一个等于“RemoveMe”的值,那该怎么办?

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

This should get you started!

你应该开始了!

#2


18  

var myArr1 = [AnyObject]()

can store any object

可以存储任何对象

var myArr2 = [String]()

can store only string

只能存储字符串

#3


16  

You could use

您可以使用

var firstNames: [String] = []

#4


12  

Swift 3

斯威夫特3

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

有三种方法可以快速地创建一个空数组,并且使用快速语法创建空数组。

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> = []

#5


10  

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

在swift中有两种主要的方法来创建/初始化数组。

var myArray = [Double]()

This would create an array of Doubles.

这将创建一个double数组。

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个double的数组,所有这些都用2.0的值初始化。

#6


4  

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

#7


2  

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

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

Array can be initialized as :

数组可初始化为:

let emptyArray = [String]()

让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"]

食品杂货清单:[String] =["鸡蛋","牛奶"]

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)用于检查计数属性是否为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个项目

#8


2  

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)

#9


0  

Array(repeating: 0, count: 10). I often use this for mapping statements where I need a specified number of mock objects. For example,

数组(重复:0,数:10)。在需要指定数量的模拟对象的情况下,我经常将其用于映射语句。例如,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

让MyObject: [MyObject] =数组(重复:0,计数:10)。映射{_ in return MyObject()}

#1


167  

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.removeAtIndex(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"?

但如果你没有呢?如果你的数组有数百个值,你只知道你想要移除一个等于“RemoveMe”的值,那该怎么办?

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

This should get you started!

你应该开始了!

#2


18  

var myArr1 = [AnyObject]()

can store any object

可以存储任何对象

var myArr2 = [String]()

can store only string

只能存储字符串

#3


16  

You could use

您可以使用

var firstNames: [String] = []

#4


12  

Swift 3

斯威夫特3

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

有三种方法可以快速地创建一个空数组,并且使用快速语法创建空数组。

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> = []

#5


10  

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

在swift中有两种主要的方法来创建/初始化数组。

var myArray = [Double]()

This would create an array of Doubles.

这将创建一个double数组。

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个double的数组,所有这些都用2.0的值初始化。

#6


4  

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

#7


2  

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

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

Array can be initialized as :

数组可初始化为:

let emptyArray = [String]()

让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"]

食品杂货清单:[String] =["鸡蛋","牛奶"]

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)用于检查计数属性是否为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个项目

#8


2  

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)

#9


0  

Array(repeating: 0, count: 10). I often use this for mapping statements where I need a specified number of mock objects. For example,

数组(重复:0,数:10)。在需要指定数量的模拟对象的情况下,我经常将其用于映射语句。例如,

let myObjects: [MyObject] = Array(repeating: 0, count: 10).map { _ in return MyObject() }

让MyObject: [MyObject] =数组(重复:0,计数:10)。映射{_ in return MyObject()}