Compare each element in two arrays Swift - arrays

I have two arrays of strings. for example:
let arrayFirst: [String] = ["A", "A", "A", "A", "A"]
let arraySecond: [String] = ["A", "C", "A", "B", "A"]
I need to compare this two arrays each element in array and return for every sequence bool state.
For example here will be answer:
let resultArray: [Bool] = [true, false, true, false, true]
how to do it better?

You can consider using the zip function.
let resultArray = zip(arrayFirst, arraySecond).map {
return $0.0 == $0.1
}
This will work even you have arrays of different length as zip will ignore the additional elements of the longer array.

Related

Divide array into subarrays

I have the following array, I have to make sure to divide it in this way into subarray, taking into consideration the first part of the name followed by / as a criterion for subdivision, for example "name/other".
Can you give me a hand?
var a = ["origin/a", "origin/b", "origin/c", "remo/a", "remo/d", "remo/c", "next/g"]
var b = {
origin: ["a", "b", "c"],
remo: ["a", "d", "c"],
next: ["g"]
}
You could used reduce(into:_:) to do so:
let reduced = a.reduce(into: [String: [String]]()) { partialResult, currentTerm in
let components = currentTerm.components(separatedBy: "/")
guard components.count == 2 else { return }
partialResult[components[0]] = partialResult[components[0], default: [String]()] + [components[1]]
}
print(reduced)
Output:
$>["remo": ["a", "d", "c"], "next": ["g"], "origin": ["a", "b", "c"]]
One idea is like this:
First we need to separate the keys for the dictionary and all the values that need to be gathered together:
let keysValues = a
.map { $0.components(separatedBy: "/") }
.compactMap { components -> (String, String)? in
guard components.count == 2 else { return nil }
return (components.first!, components.last!)
}
Now we need to reduce that into a dictionary of [String: [String]] by grouping together the values for each key:
var dict: [String: [String]] = [:]
let answer = keysValues.reduce(into: dict) { (d, kv) in
let (k, v) = kv
d[k, default: []] += [v]
}

2D array Swift goes out of bounds when appending arrays [duplicate]

This question already has answers here:
Why is this array out of index?
(2 answers)
Closed 4 years ago.
I want to append elements from one 2D array to the another 2D array, but I get fatal error index out of bound.
the code is as follows:
var array = [["a", "b", "c"], ["d","e","f"],["g","h","i"]]
var array2 = [[String]]()
var x = array.count
var y = array[1].count
for j in 0..<x {
for i in 0..<y {
array2[j].append(array[j][i])
}
}
print(array2)
please don't tell me to just copy the array as this is not what I need, I am using this procedure to do something more complex than just copying an array.
Any suggestions as to why it goes out of bounds?
thanks
array2[j] doesn't exist as it's just an empty array.
It would be much easier to do this:
var array = [["a", "b", "c"], ["d","e","f"],["g","h","i"]]
var array2 = [[String]]()
for item in array {
array2.append(item)
}
print(array2)
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
But that is just copying the array exactly. You should provide a more precise example of what you are trying to achieve.
Another option (Which makes your current code work) is to create a 'row' in the first loop ready for insertion:
var array = [["a", "b", "c"], ["d","e","f"],["g","h","i"]]
var array2 = [[String]]()
var x = array.count
var y = array[1].count
for j in 0..<x {
array2.append([String]())
for i in 0..<y {
array2[j].append(array[j][i])
}
}
print(array2)
Which gives the same output:
[["a", "b", "c"], ["d", "e", "f"], ["g", "h", "i"]]
It is going out of bounds because array2[0] doesn't exist. You need to create an an empty array there before appending to it. Then append that array to the outer array.
var array = [["a", "b", "c"], ["d","e","f"],["g","h","i"]]
var array2 = [[String]]()
for j in 0..<array.count {
var stringArray: [String] = []
for i in 0..<array[j].count {
stringArray.append(array[j][i])
}
array2.append(stringArray)
}
print(array2)

Swift - How to get indexes of filtered items of array

let items: [String] = ["A", "B", "A", "C", "A", "D"]
items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]
Does Swift 3 support a function like whatFunction(_: Element)?
If not, what is the most efficient logic?
You can filter the indices of the array directly, it avoids the extra mapping.
let items = ["A", "B", "A", "C", "A", "D"]
let filteredIndices = items.indices.filter {items[$0] == "A"}
or as Array extension:
extension Array where Element: Equatable {
func whatFunction(_ value : Element) -> [Int] {
return self.indices.filter {self[$0] == value}
}
}
items.whatFunction("A") // -> [0, 2, 4]
items.whatFunction("B") // -> [1]
or still more generic
extension Collection where Element: Equatable {
func whatFunction(_ value : Element) -> [Index] {
return self.indices.filter {self[$0] == value}
}
}
You can create your own extension for arrays.
extension Array where Element: Equatable {
func indexes(of element: Element) -> [Int] {
return self.enumerated().filter({ element == $0.element }).map({ $0.offset })
}
}
You can simply call it like this
items.indexes(of: "A") // [0, 2, 4]
items.indexes(of: "B") // [1]
You can achieve this by chain of:
enumerated() - add indexes;
filter() out unnecessary items;
map() our indexes.
Example (works in Swift 3 - Swift 4.x):
let items: [String] = ["A", "B", "A", "C", "A", "D"]
print(items.enumerated().filter({ $0.element == "A" }).map({ $0.offset })) // -> [0, 2, 4]
Another way is using flatMap, which allows you to check the element and return index if needed in one closure.
Example (works in Swift 3 - Swift 4.0):
print(items.enumerated().flatMap { $0.element == "A" ? $0.offset : nil }) // -> [0, 2, 4]
But since Swift 4.1 flatMap that can return non-nil objects become deprecated and instead you should use compactMap.
Example (works since Swift 4.1):
print(items.enumerated().compactMap { $0.element == "A" ? $0.offset : nil }) // -> [0, 2, 4]
And the cleanest and the most memory-cheap way is to iterate through array indices and check if element of array at current index equals to required element.
Example (works in Swift 3 - Swift 5.x):
print(items.indices.filter({ items[$0] == "A" })) // -> [0, 2, 4]
In Swift 3 and Swift 4 you can do that:
let items: [String] = ["A", "B", "A", "C", "A", "D"]
extension Array where Element: Equatable {
func indexes(of item: Element) -> [Int] {
return enumerated().compactMap { $0.element == item ? $0.offset : nil }
}
}
items.indexes(of: "A")
I hope my answer was helpful 😊
you can use it like that :
let items: [String] = ["A", "B", "A", "C", "A", "D"]
let indexes = items.enumerated().filter {
$0.element == "A"
}.map{$0.offset}
print(indexes)
just copy and paste
extension Array {
func whatFunction(_ ids : String) -> [Int] {
var mutableArr = [Int]()
for i in 0..<self.count {
if ((self[i] as! String) == ids) {
mutableArr.append(i)
}
}
return mutableArr
}
}
You can use that below code:
var firstArray = ["k","d","r","r","p","k","b","p","k","k"]
var secondArray = ["k","d","r","s","d","r","b","c"]
let filterArray = firstArray.filter { secondArray.contains($0) }
let filterArray1 = firstArray.filter { !secondArray.contains($0) }
let filterIndex = firstArray.enumerated().filter { $0.element == "k" }.map { $0.offset }
print(filterArray) --> // ["k", "d", "r", "r", "k", "b", "k", "k"]
print(filterArray1) --> // ["p", "p"]
print(filterIndex) --> // [0, 5, 8, 9]
this can be a way too
// MARK: - ZIP: Dictionary like
let words = ["One", "Two", "Three", "Four"]
let numbers = 1...words.count
for (word, number) in zip(words, numbers) {
print("\n\(word): \(number)")
}
For example finding the indices of p_last values that are in inds1 array: (swift 4+)
let p_last = [51,42]
let inds1 = [1,3,51,42,4]
let idx1 = Array(inds1.filter{ p_last.contains($0) }.indices)
idx1 = [0,1]

Swift 3 - Check if a string exist inside an array and sort it

I have this special array var myArray : [Array<String>] = [["a"],["b"],["c"]]
I want to detect if "a" is already inside myArray
and after i would like to sort my array alphabetically but i havn't found any function to do all these things for my array
To find if your [[String]] contains "a", you can use contains twice:
var myArray : [Array<String>] = [["a"],["b"],["c"]]
if myArray.contains(where: { $0.contains("a") }) {
print("a found")
}
To sort the inner arrays, apply map to the outer array and sort each element:
var myArray : [Array<String>] = [["c", "a"], ["e", "b"], ["d"]]
let sorted = myArray.map { $0.sorted() }
print(sorted)
[["a", "c"], ["b", "e"], ["d"]]

Xcode Swift check if array contains object

I have this array :
var preferiti : [ModalHomeLine!] = []
I want to check if the array contains the same object.
if the object exists {
} else {
var addPrf = ModalHomeLine(titolo: nomeLinea, link: linkNumeroLinea, immagine : immagine, numero : titoloLinea)
preferiti.append(addPrf)
}
Swift has a generic contains function:
contains([1,2,3,4],0) -> false
contains([1,2,3,4],3) -> true
So it sounds like you want an array without duplicate objects. In cases like this, a set is what you want. Surprisingly, Swift doesn't have a set, so you can either create your own or use NSSet, which would look something like this:
let myset = NSMutableSet()
myset.addObject("a") // ["a"]
myset.addObject("b") // ["a", "b"]
myset.addObject("c") // ["a", "b", "c"]
myset.addObject("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.
UPDATE:
Swift 1.2 added a set type! Now you can do something like
let mySet = Set<String>()
mySet.insert("a") // ["a"]
mySet.insert("b") // ["a", "b"]
mySet.insert("c") // ["a", "b", "c"]
mySet.insert("a") // ["a", "b", "c"] NOTE: this doesn't do anything because "a" is already in the set.

Resources