Array Push

From SwiftAPI

Jump to: navigation, search

Append an element to the end of an array.

Contents

C++

int values[] = {1, 2, 3};
vector<int> a(values, values + sizeof(values) / sizeof(int));
a.push_back(4);

C#

List<int> a = new List<int>() { 1, 2, 3 };
a.Add(4);
// a == { 1, 2, 3, 4 }

Java

For Lists:

import java.util.*;
 
List<Integer> a = new ArrayList<Integer>(Arrays.asList(1, 2, 3));
a.add(4);
// a == [1, 2, 3, 4]

For arrays this doesn't make sense since arrays are fixed sized.

JavaScript

developer.mozilla.org

var a = [1, 2, 3];
a.push(4);
// a == [1, 2, 3, 4]

Objective-C

Modifying a mutable array: developer.apple.com

- (void)addObject:(id)anObject
NSMutableArray *a = [NSMutableArray arrayWithObjects:@1, @2, @3, nil];
[a addObject:@4];
// a == [1, 2, 3, 4]

Creating a new array without modifying: developer.apple.com

- (NSArray *)arrayByAddingObject:(id)anObject
NSArray *a = @[@1, @2, @3];
a = [a arrayByAddingObject:@4];
// a == [1, 2, 3, 4]

Perl

perldoc

push ARRAY,LIST
@a = (1, 2, 3);
push(@a, 4);
# @a == (1, 2, 3, 4)

PHP

[] operator

$a = array(1, 2, 3);
$a[] = 4;
// $a == array(1, 2, 3, 4)

array_push

php.net

int array_push ( array &$array , mixed $var [, mixed $... ] )
$a = array(1, 2, 3);
array_push($a, 4);
// $a == array(1, 2, 3, 4);

Python

a = [1, 2, 3]
a.append(4)
# a == [1, 2, 3, 4]

Ruby

Ruby-Doc.org

array << obj -> array
a = [1, 2, 3]
a << 4
# a == [1, 2, 3, 4]

Swift

var a = [1, 2, 3]
a.append(4)
// a == [1, 2, 3, 4]
Personal tools