[ios] Add an element to an array in Swift

Suppose I have an array, for example:

var myArray = ["Steve", "Bill", "Linus", "Bret"]

And later I want to push/append an element to the end of said array, to get:

["Steve", "Bill", "Linus", "Bret", "Tim"]

What method should I use?

And what about the case where I want to add an element to the front of the array? Is there a constant time unshift?

This question is related to ios arrays swift

The answer is


Here is a small extension if you wish to insert at the beginning of the array without loosing the item at the first position

extension Array{
    mutating func appendAtBeginning(newItem : Element){
        let copy = self
        self = []
        self.append(newItem)
        self.appendContentsOf(copy)
    }
}

Example: students = ["Ben" , "Ivy" , "Jordell"]

1) To add single elements to the end of an array, use the append(_:)

students.append(\ "Maxime" )

2) Add multiple elements at the same time by passing another array or a sequence of any kind to the append(contentsOf:) method

students.append(contentsOf: ["Shakia" , "William"])

3) To add new elements in the middle of an array by using the insert(_:at:) method for single elements

students.insert("Liam" , at:2 )

4) Using insert(contentsOf:at:) to insert multiple elements from another collection or array literal

students.insert(['Tim','TIM' at: 2 )


If you want to append unique object, you can expand Array struct

extension Array where Element: Equatable {
    mutating func appendUniqueObject(object: Generator.Element) {
        if contains(object) == false {
            append(object)
        }
    }
}

In Swift 4.1 and Xcode 9.4.1

We can add objects to Array basically in Two ways

let stringOne = "One"
let strigTwo = "Two"
let stringThree = "Three"
var array:[String] = []//If your array is string type

Type 1)

//To append elements at the end
array.append(stringOne)
array.append(stringThree)

Type 2)

//To add elements at specific index
array.insert(strigTwo, at: 1)

If you want to add two arrays

var array1 = [1,2,3,4,5]
let array2 = [6,7,8,9]

let array3 = array1+array2
print(array3)
array1.append(contentsOf: array2)
print(array1)

To add to the end, use the += operator:

myArray += ["Craig"]
myArray += ["Jony", "Eddy"]

That operator is generally equivalent to the append(contentsOf:) method. (And in really old Swift versions, could append single elements, not just other collections of the same element type.)

There's also insert(_:at:) for inserting at any index.

If, say, you'd like a convenience function for inserting at the beginning, you could add it to the Array class with an extension.


In Swift 4.2: You can use

myArray.append("Tim") //To add "Tim" into array

or

myArray.insert("Tim", at: 0) //Change 0 with specific location 

To add to the solutions suggesting append, it's useful to know that this is an amortised constant time operation in many cases:

Complexity: Amortized O(1) unless self's storage is shared with another live array; O(count) if self does not wrap a bridged NSArray; otherwise the efficiency is unspecified.

I'm looking for a cons like operator for Swift. It should return a new immutable array with the element tacked on the end, in constant time, without changing the original array. I've not yet found a standard function that does this. I'll try to remember to report back if I find one!


You can also pass in a variable and/or object if you wanted to.

var str1:String = "John"
var str2:String = "Bob"

var myArray = ["Steve", "Bill", "Linus", "Bret"]

//add to the end of the array with append
myArray.append(str1)
myArray.append(str2)

To add them to the front:

//use 'insert' instead of append
myArray.insert(str1, atIndex:0)
myArray.insert(str2, atIndex:0)

//Swift 3
myArray.insert(str1, at: 0)
myArray.insert(str2, at: 0)

As others have already stated, you can no longer use '+=' as of xCode 6.1


If the array is NSArray you can use the adding function to add any object at the end of the array, like this:

Swift 4.2

var myArray: NSArray = []
let firstElement: String = "First element"
let secondElement: String = "Second element"

// Process to add the elements to the array
myArray.adding(firstElement)
myArray.adding(secondElement)

Result:

print(myArray) 
// ["First element", "Second element"]

That is a very simple way, regards!


Use += and + operators :

extension Array {

}

func += <V> (inout left: [V], right: V) {
    left.append(right)
}

func + <V>(left: Array<V>, right: V) -> Array<V>
{
    var map = Array<V>()
    for (v) in left {
        map.append(v)
    }

    map.append(right)

    return map
}

then use :

var list = [AnyObject]()
list += "hello" 
list += ["hello", "world!"]
var list2 = list + "anything"

From page 143 of The Swift Programming Language:

You can add a new item to the end of an array by calling the array’s append method

Alternatively, add a new item to the end of an array with the addition assignment operator (+=)

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. https://itun.es/us/jEUH0.l


Swift 5.3, I believe.

The normal array wasvar myArray = ["Steve", "Bill", "Linus", "Bret"] and you want to add "Tim" to the array, then you can use myArray.insert("Tim", at=*index*)so if you want to add it at the back of the array, then you can use myArray.append("Tim", at: 3)


You could use

Myarray.insert("Data #\(index)", atIndex: index)

Examples related to ios

Adding a UISegmentedControl to UITableView Crop image to specified size and picture location Undefined Symbols error when integrating Apptentive iOS SDK via Cocoapods Keep placeholder text in UITextField on input in IOS Accessing AppDelegate from framework? Autoresize View When SubViews are Added Warp \ bend effect on a UIView? Speech input for visually impaired users without the need to tap the screen make UITableViewCell selectable only while editing Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

Examples related to arrays

PHP array value passes to next row Use NSInteger as array index How do I show a message in the foreach loop? Objects are not valid as a React child. If you meant to render a collection of children, use an array instead Iterating over arrays in Python 3 Best way to "push" into C# array Sort Array of object by object field in Angular 6 Checking for duplicate strings in JavaScript array what does numpy ndarray shape do? How to round a numpy array?

Examples related to swift

Make a VStack fill the width of the screen in SwiftUI Xcode 10.2.1 Command PhaseScriptExecution failed with a nonzero exit code Command CompileSwift failed with a nonzero exit code in Xcode 10 Convert Json string to Json object in Swift 4 iOS Swift - Get the Current Local Time and Date Timestamp Xcode 9 Swift Language Version (SWIFT_VERSION) How do I use Safe Area Layout programmatically? How can I use String substring in Swift 4? 'substring(to:)' is deprecated: Please use String slicing subscript with a 'partial range from' operator Safe Area of Xcode 9 The use of Swift 3 @objc inference in Swift 4 mode is deprecated?