How to create an empty array in Swift?

IosArraysSwift

Ios Problem Overview


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 Solutions


Solution 1 - Ios

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!

Solution 2 - Ios

Swift 5

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

Method 1: Shorthand Syntax

var arr = [Int]()

Method 2: Array Initializer

var arr = Array<Int>()

Method 3: Array with an Array Literal

var arr:[Int] = []

Method 4: Credit goes to @BallpointBen

var arr:Array<Int> = []

Solution 3 - Ios

var myArr1 = [AnyObject]()

can store any object

var myArr2 = [String]()

can store only string

Solution 4 - Ios

You could use

var firstNames: [String] = []

Solution 5 - Ios

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.

Solution 6 - Ios

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

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

Solution 7 - Ios

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

Solution 8 - Ios

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

Array can be initialized as :

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.

For Creating the array of type string with elements

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.

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:

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:

groceryList.append("Flour")

groceryList now contains 3 items.

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

groceryList += ["Baking Powder"]

groceryList now contains 4 items

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

groceryList now contains 7 items

Solution 9 - Ios

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

Solution 10 - Ios

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)

Solution 11 - Ios

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() }

Solution 12 - Ios

Swift 5

// Create an empty array
var emptyArray = [String]()

// Add values to array by appending (Adds values as the last element)
emptyArray.append("Apple")
emptyArray.append("Oppo")

// Add values to array by inserting (Adds to a specified position of the list)
emptyArray.insert("Samsung", at: 0)

// Remove elements from an array by index number
emptyArray.remove(at: 2)

// Remove elements by specifying the element
if let removeElement = emptyArray.firstIndex(of: "Samsung") {
    emptyArray.remove(at: removeElement)
}

A similar answer is given but that doesn't work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)

Solution 13 - Ios

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.

Solution 14 - Ios

Swift 5 version:

let myArray1: [String] = []
let myArray2: [String] = [String]()
let myArray3 = [String]()
let myArray4: Array<String> = Array()

Or more elegant way:

let myElegantArray1: [String] = .init()

extension Array {
    static func empty() -> Self {
        return []
    }
}

let myElegantArray2: [String] = .empty()

The extension above, you can use for any type Array

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionInuyashaView Question on Stackoverflow
Solution 1 - IosDave GView Answer on Stackoverflow
Solution 2 - IosX.CreatesView Answer on Stackoverflow
Solution 3 - IosvichhaiView Answer on Stackoverflow
Solution 4 - IosDPenView Answer on Stackoverflow
Solution 5 - IosAaronView Answer on Stackoverflow
Solution 6 - Iospiyush ranjanView Answer on Stackoverflow
Solution 7 - IosBobbyView Answer on Stackoverflow
Solution 8 - IosABSView Answer on Stackoverflow
Solution 9 - IosManoj PerumarathView Answer on Stackoverflow
Solution 10 - IosUllas PujaryView Answer on Stackoverflow
Solution 11 - IosthexandeView Answer on Stackoverflow
Solution 12 - IosAbdullah AjmalView Answer on Stackoverflow
Solution 13 - IosCrazyOneView Answer on Stackoverflow
Solution 14 - IosNazariy VlizloView Answer on Stackoverflow