How to create an empty array in Swift?

2020-01-29 03:31发布

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?

标签: ios arrays swift
13条回答
虎瘦雄心在
2楼-- · 2020-01-29 03:42

Compatible with: Xcode 6.0.1+

You can create an empty array by specifying the Element type of your array in the declaration.

For example:

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

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

Example from the apple developer page (Array):

Hope this helps anyone stumbling onto this page.

查看更多
\"骚年 ilove
3楼-- · 2020-01-29 03:44

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.

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

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

This should get you started!

查看更多
甜甜的少女心
4楼-- · 2020-01-29 03:46

As per 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()

查看更多
Melony?
5楼-- · 2020-01-29 03:46

Initiating an array with a predefined count:

Array(repeating: 0, count: 10)

I often use this for mapping statements where I need a specified number of mock objects. For example,

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

查看更多
别忘想泡老子
6楼-- · 2020-01-29 03:49

You could use

var firstNames: [String] = []
查看更多
Root(大扎)
7楼-- · 2020-01-29 03:50

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

    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
查看更多
登录 后发表回答