How to create an empty array in Swift?

I am really confused about how we create an array in Swift. Could you tell me how many ways to create an empty array with some details?

+133
arrays ios swift
May 25 '15 at 2:43
source share
15 answers

Here you go:

var yourArray = [String]() 

The above also works for other types, not just strings. This is just an example.

Adding Values โ€‹โ€‹to It

I assume that in the end you will want to add value to it!

 yourArray.append("String Value") 

or

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

Add by pasting

Once you have multiple values, you can insert new values โ€‹โ€‹instead of adding. For example, if you want to insert new objects at the beginning of the array (instead of adding 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 delete some content.

 var yourOtherArray = ["MonkeysRule", "RemoveMe", "SwiftRules"] yourOtherArray.removeAtIndex(1) 

The above works fine when you know where the value is in the array (i.e. when you know its index value). Since index values โ€‹โ€‹start at 0, the second entry will be indicated at index 1.

Deleting values โ€‹โ€‹without knowing the index

But what if you do not? What if yourOtherArray has hundreds of values โ€‹โ€‹and all you know is you want to remove a value equal to "RemoveMe"?

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

This should get you started!

+263
Feb 15 '16 at 22:52
source share
 var myArr1 = [AnyObject]() 

can store any object

 var myArr2 = [String]() 

can only store a string

+26
May 25 '15 at 2:52
source share

you can use

 var firstNames: [String] = [] 
+22
Mar 03 '16 at 20:33
source share

Swift 3

There are three (3) ways to create an empty array in Swift, and a shorthand syntax style is always preferable.

Method 1: Shortcut Syntax

 var arr = [Int]() 

Method 2: Array Initializer

 var arr = Array<Int>() 

Method 3: array with array literal

 var arr:[Int] = [] 

Method 4. Credit is sent to @BallpointBen

 var arr:Array<Int> = [] 
+21
Feb 26 '17 at 3:09 on
source share

There are two main ways to create / initialize an array in swift.

 var myArray = [Double]() 

This will create an array of pair numbers.

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

This will create an array of 5 doubles, all initialized to 2.0.

+17
May 25 '15 at 2:46
source share

If you want to declare an empty array of string type, you can do this in 5 different ways: -

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

An array of type Integer: -

  var myArray: Array<Int> = Array() var myArray = [Int]() var myArray: [Int] = [] var myArray = Array<Int>() var myArray:Array<Int> = [] 
+7
Jul 10 '18 at 6:45
source share

Here are some common tasks in Swift 4 that 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 
+6
Apr 07 '17 at 10:42 on
source share

An array in swift is written as ** Array <Element> **, where Element is the type of values โ€‹โ€‹that the array can be stored.

The array can be initialized as:

let emptyArray = [String]()

It shows that its array is a string of type

The variable type emptyArray is defined as [String] from the type of the initializer.

To create an array of type string with elements

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

The groceryList file was initialized with two items.

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

There are various array properties like:

- check if there is an array of elements (if the array is empty or not)

isEmpty property (Boolean) to check if the count property is 0:

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

- Adding (adding) elements to the array

You can add a new element to the end of the array by calling the arrays append (_ :) method:

 groceryList.append("Flour") 

The gcceryList file now contains 3 elements.

Alternatively, add an array of one or more compatible elements with the add assignment operator (+ =):

 groceryList += ["Baking Powder"] 

The groceryList file now contains 4 items

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

The gcceryList file now contains 7 elements

+3
Mar 17 '16 at 19:46
source share

you can delete the contents of the array with the transfer of the index of the array or delete everything

  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) 
+2
May 13, '16 at 17:09
source share

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 it does not work for the latest version of Swift (Swift 5), so here is the updated answer. Hope it helps! :)

+1
Jun 08 '19 at 2:39 on
source share

Initiating an array with a predefined amount:

Array(repeating: 0, count: 10)

I often use this to display statements where I need a certain number of dummy objects. For example,

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

0
Dec 08 '17 at 23:27
source share

// Simple empty array of type String

var arrString: [String] = String

0
Dec 10 '18 at 10:31
source share

swift 3 and above i hope you help you

// Declare an array of String

  var arraName = [String]() // Adding Value String Only self.arraName.append("abc") self.arraName.append("Test") self.arraName.append("pravin") self.arraName.append("Jay") print("arraName ==> \(self.arraName)") 

// Declare Store All Type Value

  var arrAllTypeValue = [Any]() //Add value allType Like Int,String,Float self.arrAllTypeValue.append(1) self.arrAllTypeValue.append("Pravin") self.arrAllTypeValue.append(12.00) print("ArrayAllTypeValue ==>\(self.arrAllTypeValue)") 
0
Jan 17 '19 at 6:54
source share

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 who stumbles on this page.

0
Jul 06 '19 at 21:42
source share

According to 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() 
0
Aug 08 '19 at 12:05
source share



All Articles