Multidimensional array - get value of each element at same time - arrays

Having issue creating the logic for this. Is it even possible ?
Let’s say you have
Var one = [[1,1,1]]
Var two = [[2,2,2]]
Var three = [[3,3,3]]
Var k = [one,two,three]
Assume you won’t know the length of var “k”.
I’m trying to write a function that will allow me to access all elements in “k” at the same time and access each index value.
Example.
k[0][0]
k[1][0]
k[2][0]
——————
k[0][1]
k[1][1]
k[2][1]
——————
I know for loops is a start but I’m stuck when it comes to accessing each element at the same time Dynamically. Is this even possible ?

Not sure what you are trying to achieve.
If you want to build a 3 x 3 matrix you can write
var one = [1,1,1]
var two = [2,2,2]
var three = [3,3,3]
var k = [one, two, three]
Now you have in memory the equivalent of this matrix
1, 1, 1
2, 2, 2
3, 3, 3
And you can access an element using this syntax
k[i][j]
where i and j are integers between 0 and 2.
Example
k[0][0] // 1
If you are looking for a good way to work with a matrix have a look here https://docs.swift.org/swift-book/LanguageGuide/Subscripts.html#subscripts

Rather than working directly against the 2D array I wrapped it in a struct Matrix where the function column(at:) will return all values in a column. The struct is generic to allow for different element types
struct Matrix<T> {
private var data: [[T]]
private init() {
data = []
}
init(rows: [T]...) {
self.init()
let check = rows.first?.count ?? 0
for row in rows {
guard row.count == check else { fatalError("All rows must be the same length")}
data.append(row)
}
}
func row(at index: Int) -> [T]? {
guard index < data.count else { return nil }
return data[index]
}
func column(at index: Int) -> [T]? {
guard !data.isEmpty else { return nil }
var column = [T]()
for i in 0..<data.count {
column.append(data[i][index])
}
return column
}
}
And it can be used like this
let matrix = Matrix(rows: [1,1,2],[2,2,2],[3,3,3])
print(matrix.column(at: 1))
print(matrix.row(at: 1))
let matrix2 = Matrix(rows: ["a", "b"], ["c", "d"], ["e", "f"],["g", "h"])
print(matrix2.column(at: 1))
print(matrix2.row(at: 1))
[1, 2, 3]
[2, 2, 2]
["b", "d", "f", "h"]
["c", "d"]

Related

Compare an array with another & then return the index of matched results

Sorry if this is a dumb question but everything I try seems to be wrong! (I am new to Swift).
I have 2 arrays of Strings which I need to compare for matches and then return an array with the index position of those matches .... IE:
let array1 = ["abc", "def", "ghi", "jkl", "xyz", "uhr"]
let array2 = ["ghi", "xyz", "uhr"]
// Search array1 for instances of array2
// Result I want is: [2, 4, 5]
Is there a simple function I am missing?! Thanks in advance for your help.
For an efficient solution you can create an index first. The index maps each element in the first array to its position in the array. Both arrays are traversed only once:
let array1 = ["abc", "def", "ghi", "jkl", "xyz", "uhr"]
let array2 = ["ghi", "xyz", "uhr"]
let index = Dictionary(uniqueKeysWithValues: array1.enumerated().map {
($0.element, $0.offset)
})
let result = array2.compactMap { index[$0] }
print(result) // [2, 4, 5]
If the elements in array1 are not known to be unique then the index must be computed slightly differently:
let index = Dictionary(array1.enumerated().map { ($0.element, $0.offset) },
uniquingKeysWith: { (first, _) in first })
The second parameter is a closure which controls which value to put into the dictionary in the case of duplicate keys. Here we choose the position of the first occurrence of an element in the array.
var indexArr: [Int] = []
for element in array2 {
if let elementIndex = array1.firstIndex(of: element) {
indexArr.append(elementIndex)
}
}
print(indexArr)
var results: [Int] = []
for i in 0..<array1.count {
for j in 0..<array2.count {
if array1[i] == array2[j] {
results.append(i)
}
}
}
print(results)

Swift Array Extension to replace value of index n by the sum of the n-previous values

I am trying to write an extension for Array Types that sums the n-previous indexes in the index n.
let myArray = [1, 2, 3, 4, 5]
let mySumArray = myArray.sumNIndex()
print(mySumArray)
// returns [1,3,6,10,15]
I have tried various approaches which all failed at some point.
For instance, the example hereafter triggers a compile error
"Cannot invoke 'reduce' with an argument list of type '(Int, _)'":
extension Array {
mutating func indexSum() {
var tempArray = [Any]()
for index in 1...self.count - 1 {
self[index] += self[.prefix(index + 2).reduce(0, +)]
}
}
}
This other attempt triggers another compile error:
"Binary operator '+=' cannot be applied to two 'Element' operands"
extension Array {
mutating func indexSum() {
var tempArray = [Any]()
for index in 1...self.count - 1 {
self[index] += self[index - 1]
}
}
}
Any idea is welcome!
Thank you very much for your help!
EDIT: Many thanks to #Martin and #Carpsen who figured it out in 2 different ways
#Martin using map method:
extension Array where Element: Numeric {
func cumulativeSum() -> [Element] {
var currentSum: Element = 0
return map {
currentSum += $0
return currentSum
}
}
}
#Carpsen using reduce method:
extension Array where Element: Numeric {
func indexSum() -> [Element] {
return self.reduce(into: [Element]()) {(acc, element) in
return acc + [(acc.last ?? 0) + element]
})
}
}
The main problem is that the addition operator + is not defined for elements
of arbitrary arrays. You need to restrict the extension method, e.g. to
arrays of Numeric elements.
Also there is no need to use Any.
Here is a possible implementation as a non-mutating method:
extension Array where Element: Numeric {
func cumulativeSum() -> [Element] {
var currentSum: Element = 0
return map {
currentSum += $0
return currentSum
}
}
}
Examples:
let intArray = [1, 2, 3, 4, 5]
print(intArray.cumulativeSum()) // [1, 3, 6, 10, 15]
let floatArray = [1.0, 2.5, 3.25]
print(floatArray.cumulativeSum()) [1.0, 3.5, 6.75]
In a similar fashion we can “cumulatively join” the elements of a
string array. enumerated() is now used to provide the current element
index together with the element, and that is used to decide whether to
insert the separator or not:
extension Array where Element == String {
func cumulativeJoin(separator: String) -> [Element] {
var currentJoin = ""
return enumerated().map { (offset, elem) in
if offset > 0 { currentJoin.append(separator) }
currentJoin.append(elem)
return currentJoin
}
}
}
Examples:
let stringArray = ["a", "b", "c"]
print(stringArray.cumulativeJoin()) // ["a", "ab", "abc"]
print(stringArray.cumulativeJoin(separator: ":")) // ["a", "a:b", "a:b:c"]
Try this:
let myArray = [1, 2, 3, 4, 5]
myArray.reduce([Int](), {accumulator, element in
return accumulator + [(accumulator.last ?? 0) + element]
})
//[1, 3, 6, 10, 15]
What this reduce does is:
Start with an empty array
With each element from myArray it calculates its sum with the last element in the accumulator
Return the previous array plus the last sum
Here is a simpler, but longer version:
let myArray = [1, 2, 3, 4, 5]
let newArray = myArray.reduce([Int](), {accumulator, element in
var tempo = accumulator
let lastElementFromTheAccumulator = accumulator.last ?? 0
let currentSum = element + lastElementFromTheAccumulator
tempo.append(currentSum)
return tempo
})
print(newArray) //[1, 3, 6, 10, 15]
A more efficient solution, as suggested by Martin R in the comments, uses reduce(into:):
myArray.reduce(into: [Int]()) { (accumulator, element) in
accumulator += [(accumulator.last ?? 0) + element]
}
//[1, 3, 6, 10, 15]
And you could have it as an extension:
extension Array where Element: Numeric {
func indexSum() -> [Element] {
return self.reduce([Element](), {acc, element in
return acc + [(acc.last ?? 0) + element]
})
}
}
myArray.indexSum() //[1, 3, 6, 10, 15]
Here a solution that will work with strings too:
extension Array where Element == String {
func indexSum() -> [String] {
return self.reduce(into: [String]()) {(accumulator, element) in
accumulator += [(accumulator.last ?? "") + element]
}
}
}
["a", "b", "c", "d"].indexSum() //["a", "ab", "abc", "abcd"]
If you'd like to have a separator between the elements of the initial array elements, you could use this extension:
extension Array where Element == String {
func indexSum(withSparator: String) -> [String] {
return self.reduce(into: [String]()) {(accumulator, element) in
var previousString = ""
if let last = accumulator.last {
previousString = last + " "
}
accumulator += [previousString + element]
}
}
}
["a", "b", "c", "d"].indexSum(withSparator: " ") //["a", "a b", "a b c", "a b c d"]

How to split an array in half in Swift?

How do I split a deck of cards? I have an array made and a random card dealer, but have no idea how to split the deck.
Thanks everyone for the help! I now have a working card app, did run into other problems but they were solved quickly.
You can make an extension so it can return an array of two arrays, working with Ints, Strings, etc:
extension Array {
func split() -> [[Element]] {
let ct = self.count
let half = ct / 2
let leftSplit = self[0 ..< half]
let rightSplit = self[half ..< ct]
return [Array(leftSplit), Array(rightSplit)]
}
}
let deck = ["J", "Q", "K", "A"]
let nums = [0, 1, 2, 3, 4]
deck.split() // [["J", "Q"], ["K", "A"]]
nums.split() // [[0, 1], [2, 3, 4]]
But returning a named tuple is even better, because it enforces the fact that you expect exactly two arrays as a result:
extension Array {
func split() -> (left: [Element], right: [Element]) {
let ct = self.count
let half = ct / 2
let leftSplit = self[0 ..< half]
let rightSplit = self[half ..< ct]
return (left: Array(leftSplit), right: Array(rightSplit))
}
}
let deck = ["J", "Q", "K", "A"]
let splitDeck = deck.split()
print(splitDeck.left) // ["J", "Q"]
print(splitDeck.right) // ["K", "A"]
Note: credits goes to Andrei and Qbyte for giving the first correct answer, I'm just adding info.
You can use subscript range
let deck: [String] = ["J", "Q", "K", "A"]
// use ArraySlice only for transient computation
let leftSplit: ArraySlice<String> = deck[0 ..< deck.count / 2] // "J", "Q"
let rightSplit: ArraySlice<String> = deck[deck.count / 2 ..< deck.count] // "K", "A"
// make arrays from ArraySlice
let leftDeck: [String] = Array(leftSplit) // "J", "Q"
let rightDeck: [String] = Array(rightSplit) // "K", "A"
EDIT: above code is for Swift 2, maybe for Swift 3 is a more convenient way.
Swift
More generic solution to split the array into chunks the answer from this link
extension Array {
func chunked(into size: Int) -> [[Element]] {
return stride(from: 0, to: count, by: size).map {
Array(self[$0 ..< Swift.min($0 + size, count)])
}
}
}
let numbers = Array(1...100)
let result = numbers.chunked(into: 5)
And one more realization of previously provided ideas. Firstly, up to Swift current documentation, it is better to choose names in past simple tense for functions that produce some result and present tense for mutating ones.
As second, as for me, it is better to choose half adding count % 2 to give more uniformed result.
Here is it:
extension Array {
func devided() -> ([Element], [Element]) {
let half = count / 2 + count % 2
let head = self[0..<half]
let tail = self[half..<count]
return (Array(head), Array(tail))
}
}
And results:
let set1 = [1, 2, 3, 4, 5, 6, 7,8]
let set2 = [1, 2, 3, 4, 5]
let set3 = [1]
let set4 = [Int]()
print(set1.devided())
print(set2.devided())
print(set3.devided())
print(set4.devided())
([1, 2, 3, 4], [5, 6, 7, 8])
([1, 2, 3], [4, 5])
([1], [])
([], [])
You can create an extension on SequenceType, and create a function named divide.
This function would iterate through the elements of the sequence while placing those that match the predicate into one array (slice) and those that do not match into another array (remainder).
The function returns a tuple containing the slice and the remainder.
extension SequenceType {
/**
Returns a tuple with 2 arrays.
The first array (the slice) contains the elements of self that match the predicate.
The second array (the remainder) contains the elements of self that do not match the predicate.
*/
func divide(#noescape predicate: (Self.Generator.Element) -> Bool) -> (slice: [Self.Generator.Element], remainder: [Self.Generator.Element]) {
var slice: [Self.Generator.Element] = []
var remainder: [Self.Generator.Element] = []
forEach {
switch predicate($0) {
case true : slice.append($0)
case false : remainder.append($0)
}
}
return (slice, remainder)
}
}
This is an example
let tuple = [1, 2, 3, 4, 5].divide({ $0 >= 3 })
tuple.slice // [3, 4, 5]
tuple.remainder // [1, 2]

Removing objects from an array based on another array

I have two arrays like this:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
As you can see, James and Steve match and I want to be able to remove them from arrayA. How would I write this?
#francesco-vadicamo's answer in Swift 2/3/4+
arrayA = arrayA.filter { !arrayB.contains($0) }
The easiest way is by using the new Set container (added in Swift 1.2 / Xcode 6.3):
var setA = Set(arrayA)
var setB = Set(arrayB)
// Return a set with all values contained in both A and B
let intersection = setA.intersect(setB)
// Return a set with all values in A which are not contained in B
let diff = setA.subtract(setB)
If you want to reassign the resulting set to arrayA, simply create a new instance using the copy constructor and assign it to arrayA:
arrayA = Array(intersection)
The downside is that you have to create 2 new data sets.
Note that intersect doesn't mutate the instance it is invoked in, it just returns a new set.
There are similar methods to add, subtract, etc., you can take a look at them
Like this:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
if let ix = find(arrayA, word) {
arrayA.removeAtIndex(ix)
}
}
// now arrayA is ["Mike", "Stacey"]
I agree with Antonio's answer, however for small array subtractions you can also use a filter closure like this:
let res = arrayA.filter { !contains(arrayB, $0) }
matt and freytag's solutions are the ONLY ones that account for duplicates and should be receiving more +1s than the other answers.
Here is an updated version of matt's answer for Swift 3.0:
var arrayA = ["Mike", "James", "Stacey", "Steve"]
var arrayB = ["Steve", "Gemma", "James", "Lucy"]
for word in arrayB {
if let ix = arrayA.index(of: word) {
arrayA.remove(at: ix)
}
}
Original answer
This can also be implemented as a minus func:
func -<T:RangeReplaceableCollectionType where T.Generator.Element:Equatable>( lhs:T, rhs:T ) -> T {
var lhs = lhs
for element in rhs {
if let index = lhs.indexOf(element) { lhs.removeAtIndex(index) }
}
return lhs
}
Now you can use
arrayA - arrayB
Updated implementation for Swift 5
func -<T: RangeReplaceableCollection>(lhs: T, rhs: T) -> T where T.Iterator.Element: Equatable {
var lhs = lhs
for element in rhs {
if let index = lhs.firstIndex(of: element) { lhs.remove(at: index) }
}
return lhs
}
Using the Array → Set → Array method mentioned by Antonio, and with the convenience of an operator, as freytag pointed out, I've been very satisfied using this:
// Swift 3.x/4.x
func - <Element: Hashable>(lhs: [Element], rhs: [Element]) -> [Element]
{
return Array(Set<Element>(lhs).subtracting(Set<Element>(rhs)))
}
For smaller arrays I use:
/* poormans sub for Arrays */
extension Array where Element: Equatable {
static func -=(lhs: inout Array, rhs: Array) {
rhs.forEach {
if let indexOfhit = lhs.firstIndex(of: $0) {
lhs.remove(at: indexOfhit)
}
}
}
static func -(lhs: Array, rhs: Array) -> Array {
return lhs.filter { return !rhs.contains($0) }
}
}
Remove elements using indexes array:
Array of Strings and indexes
let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
let indexAnimals = [0, 3, 4]
let arrayRemainingAnimals = animals
.enumerated()
.filter { !indexAnimals.contains($0.offset) }
.map { $0.element }
print(arrayRemainingAnimals)
//result - ["dogs", "chimps", "cow"]
Array of Integers and indexes
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let indexesToRemove = [3, 5, 8, 12]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
print(numbers)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Remove elements using element value of another array
Arrays of integers
let arrayResult = numbers.filter { element in
return !indexesToRemove.contains(element)
}
print(arrayResult)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Arrays of strings
let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
let arrayRemoveLetters = ["a", "e", "g", "h"]
let arrayRemainingLetters = arrayLetters.filter {
!arrayRemoveLetters.contains($0)
}
print(arrayRemainingLetters)
//result - ["b", "c", "d", "f", "i"]

How to remove an element from an array in Swift

How can I unset/remove an element from an array in Apple's new language Swift?
Here's some code:
let animals = ["cats", "dogs", "chimps", "moose"]
How could the element animals[2] be removed from the array?
The let keyword is for declaring constants that can't be changed. If you want to modify a variable you should use var instead, e.g:
var animals = ["cats", "dogs", "chimps", "moose"]
animals.remove(at: 2) //["cats", "dogs", "moose"]
A non-mutating alternative that will keep the original collection unchanged is to use filter to create a new collection without the elements you want removed, e.g:
let pets = animals.filter { $0 != "chimps" }
Given
var animals = ["cats", "dogs", "chimps", "moose"]
Remove first element
animals.removeFirst() // "cats"
print(animals) // ["dogs", "chimps", "moose"]
Remove last element
animals.removeLast() // "moose"
print(animals) // ["cats", "dogs", "chimps"]
Remove element at index
animals.remove(at: 2) // "chimps"
print(animals) // ["cats", "dogs", "moose"]
Remove element of unknown index
For only one element
if let index = animals.firstIndex(of: "chimps") {
animals.remove(at: index)
}
print(animals) // ["cats", "dogs", "moose"]
For multiple elements
var animals = ["cats", "dogs", "chimps", "moose", "chimps"]
animals = animals.filter(){$0 != "chimps"}
print(animals) // ["cats", "dogs", "moose"]
Notes
The above methods modify the array in place (except for filter) and return the element that was removed.
Swift Guide to Map Filter Reduce
If you don't want to modify the original array, you can use dropFirst or dropLast to create a new array.
Updated to Swift 5.2
The above answers seem to presume that you know the index of the element that you want to delete.
Often you know the reference to the object you want to delete in the array. (You iterated through your array and have found it, e.g.) In such cases it might be easier to work directly with the object reference without also having to pass its index everywhere. Hence, I suggest this solution. It uses the identity operator !==, which you use to test whether two object references both refer to the same object instance.
func delete(element: String) {
list = list.filter { $0 != element }
}
Of course this doesn't just work for Strings.
Swift 5:
Here is a cool and easy extension to remove elements in an array, without filtering :
extension Array where Element: Equatable {
// Remove first collection element that is equal to the given `object`:
mutating func remove(object: Element) {
guard let index = firstIndex(of: object) else {return}
remove(at: index)
}
}
Usage :
var myArray = ["cat", "barbecue", "pancake", "frog"]
let objectToRemove = "cat"
myArray.remove(object: objectToRemove) // ["barbecue", "pancake", "frog"]
Also works with other types, such as Int since Element is a generic type:
var myArray = [4, 8, 17, 6, 2]
let objectToRemove = 17
myArray.remove(object: objectToRemove) // [4, 8, 6, 2]
For Swift4:
list = list.filter{$0 != "your Value"}
As of Xcode 10+, and according to the WWDC 2018 session 223, "Embracing Algorithms," a good method going forward will be mutating func removeAll(where predicate: (Element) throws -> Bool) rethrows
Apple's example:
var phrase = "The rain in Spain stays mainly in the plain."
let vowels: Set<Character> = ["a", "e", "i", "o", "u"]
phrase.removeAll(where: { vowels.contains($0) })
// phrase == "Th rn n Spn stys mnly n th pln."
see Apple's Documentation
So in the OP's example, removing animals[2], "chimps":
var animals = ["cats", "dogs", "chimps", "moose"]
animals.removeAll(where: { $0 == "chimps" } )
// or animals.removeAll { $0 == "chimps" }
This method may be preferred because it scales well (linear vs quadratic), is readable and clean. Keep in mind that it only works in Xcode 10+, and as of writing this is in Beta.
If you have array of custom Objects, you can search by specific property like this:
if let index = doctorsInArea.firstIndex(where: {$0.id == doctor.id}){
doctorsInArea.remove(at: index)
}
or if you want to search by name for example
if let index = doctorsInArea.firstIndex(where: {$0.name == doctor.name}){
doctorsInArea.remove(at: index)
}
You could do that. First make sure Dog really exists in the array, then remove it. Add the for statement if you believe Dog may happens more than once on your array.
var animals = ["Dog", "Cat", "Mouse", "Dog"]
let animalToRemove = "Dog"
for object in animals {
if object == animalToRemove {
animals.remove(at: animals.firstIndex(of: animalToRemove)!)
}
}
If you are sure Dog exits in the array and happened only once just do that:
animals.remove(at: animals.firstIndex(of: animalToRemove)!)
If you have both, strings and numbers
var array = [12, 23, "Dog", 78, 23]
let numberToRemove = 23
let animalToRemove = "Dog"
for object in array {
if object is Int {
// this will deal with integer. You can change to Float, Bool, etc...
if object == numberToRemove {
array.remove(at: array.firstIndex(of: numberToRemove)!)
}
}
if object is String {
// this will deal with strings
if object == animalToRemove {
array.remove(at: array.firstIndex(of: animalToRemove)!)
}
}
}
If you don't know the index of the element that you want to remove, and the element is conform the Equatable protocol, you can do:
animals.remove(at: animals.firstIndex(of: "dogs")!)
See Equatable protocol answer:How do I do indexOfObject or a proper containsObject
Few Operation relates to Array in Swift
Create Array
var stringArray = ["One", "Two", "Three", "Four"]
Add Object in Array
stringArray = stringArray + ["Five"]
Get Value from Index object
let x = stringArray[1]
Append Object
stringArray.append("At last position")
Insert Object at Index
stringArray.insert("Going", at: 1)
Remove Object
stringArray.remove(at: 3)
Concat Object value
var string = "Concate Two object of Array \(stringArray[1]) + \(stringArray[2])"
Remove elements using indexes array:
Array of Strings and indexes
let animals = ["cats", "dogs", "chimps", "moose", "squarrel", "cow"]
let indexAnimals = [0, 3, 4]
let arrayRemainingAnimals = animals
.enumerated()
.filter { !indexAnimals.contains($0.offset) }
.map { $0.element }
print(arrayRemainingAnimals)
//result - ["dogs", "chimps", "cow"]
Array of Integers and indexes
var numbers = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12]
let indexesToRemove = [3, 5, 8, 12]
numbers = numbers
.enumerated()
.filter { !indexesToRemove.contains($0.offset) }
.map { $0.element }
print(numbers)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Remove elements using element value of another array
Arrays of integers
let arrayResult = numbers.filter { element in
return !indexesToRemove.contains(element)
}
print(arrayResult)
//result - [0, 1, 2, 4, 6, 7, 9, 10, 11]
Arrays of strings
let arrayLetters = ["a", "b", "c", "d", "e", "f", "g", "h", "i"]
let arrayRemoveLetters = ["a", "e", "g", "h"]
let arrayRemainingLetters = arrayLetters.filter {
!arrayRemoveLetters.contains($0)
}
print(arrayRemainingLetters)
//result - ["b", "c", "d", "f", "i"]
I came up with the following extension that takes care of removing elements from an Array, assuming the elements in the Array implement Equatable:
extension Array where Element: Equatable {
mutating func removeEqualItems(_ item: Element) {
self = self.filter { (currentItem: Element) -> Bool in
return currentItem != item
}
}
mutating func removeFirstEqualItem(_ item: Element) {
guard var currentItem = self.first else { return }
var index = 0
while currentItem != item {
index += 1
currentItem = self[index]
}
self.remove(at: index)
}
}
Usage:
var test1 = [1, 2, 1, 2]
test1.removeEqualItems(2) // [1, 1]
var test2 = [1, 2, 1, 2]
test2.removeFirstEqualItem(2) // [1, 1, 2]
Regarding #Suragch's Alternative to "Remove element of unknown index":
There is a more powerful version of "indexOf(element)" that will match on a predicate instead of the object itself. It goes by the same name but it called by myObjects.indexOf{$0.property = valueToMatch}. It returns the index of the first matching item found in myObjects array.
If the element is an object/struct, you may want to remove that element based on a value of one of its properties. Eg, you have a Car class having car.color property, and you want to remove the "red" car from your carsArray.
if let validIndex = (carsArray.indexOf{$0.color == UIColor.redColor()}) {
carsArray.removeAtIndex(validIndex)
}
Foreseeably, you could rework this to remove "all" red cars by embedding the above if statement within a repeat/while loop, and attaching an else block to set a flag to "break" out of the loop.
Swift 5
guard let index = orders.firstIndex(of: videoID) else { return }
orders.remove(at: index)
This should do it (not tested):
animals[2...3] = []
Edit: and you need to make it a var, not a let, otherwise it's an immutable constant.
extension to remove String object
extension Array {
mutating func delete(element: String) {
self = self.filter() { $0 as! String != element }
}
}
I use this extension, almost same as Varun's, but this one (below) is all-purpose:
extension Array where Element: Equatable {
mutating func delete(element: Iterator.Element) {
self = self.filter{$0 != element }
}
}
To remove elements from an array, use the remove(at:),
removeLast() and removeAll().
yourArray = [1,2,3,4]
Remove the value at 2 position
yourArray.remove(at: 2)
Remove the last value from array
yourArray.removeLast()
Removes all members from the set
yourArray.removeAll()

Resources