Swift Array manipulation examples

Appending to an array


var myArray = [1,2]
myArray.append(3)
print(myArray)
//Result = [1, 2, 3]

myArray += [4,5]
print(myArray)
//Result = [1, 2, 3, 4, 5]

Inserting a value into an array


myArray.insert(10, at: 3)
print(myArray)
//Result = [1, 2, 3, 10, 4, 5]

Replacing elements in an array


myArray[2] = 9
print(myArray)
//Result = [1, 2, 9, 10, 4, 5]

Removing elements from an array


myArray.removeLast()
print(myArray)
//Result = [1, 2, 9, 10, 4]

myArray.remove(at:2)
print(myArray)
//Result = [1, 2, 10, 4]

myArray.removeAll()
print(myArray)
//Result = [], array is now empty

Merging two arrays


let myArray1 = [1,2]
let myArray2 = [3,4]
var combinedArray = myArray1 + myArray2
print(combinedArray)
//Result = [1, 2, 3, 4]

Retrieving a subarray from an array


myArray = [1,2,3,4,5]
var mySubArray = myArray[2...4]
print(mySubArray)
//Result = [3, 4, 5]

mySubArray = myArray[2..<4]
print(mySubArray)
//Result = [3, 4]

mySubArray = myArray[..<3]
print(mySubArray)
//Result = [1, 2, 3]

mySubArray = myArray[...3]
print(mySubArray)
//Result = [1, 2, 3, 4]

mySubArray = myArray[2...]
print(mySubArray)
//Result = [3, 4, 5]


Bulk changes to an array


myArray = [1,2,3,4,5]
myArray[1...2] = [12,13]
print(myArray)
//Result = [1, 12, 13, 4, 5]

myArray = [1,2,3,4,5]
myArray[1...3] = [12,13]
print(myArray)
//Result = [1, 12, 13, 5]

myArray = [1,2,3,4,5]
myArray[1...3] = [12,13,14,15]
print(myArray)
//Result = [1, 12, 13, 14, 15, 5]


No comments:

Post a Comment

NO JUNK, Please try to keep this clean and related to the topic at hand.
Comments are for users to ask questions, collaborate or improve on existing.