This question already has answers here:
How can I flatten an array swiftily in Swift?
(4 answers)
Closed 6 years ago.
I have following data:
let array1 = [[1], [2], [3]]
And I want to make it vector:
let result = [1, 2, 3]
Solution off the top of my head:
var result = [Int]()
for arrayOfArray in array1 {
for value in arrayOfArray {
result(value)
}
}
Is there more elegant way to do this ?
You can use flatMap for that.
let array1 = [[1], [2], [3]]
let result = array1.flatMap { $0 }
Output
[1, 2, 3]
Check Apple Documentation on flatMap for more details.
Related
I have an array of numbers. I want to find those in array1 that aren't also in array2, like this:
var array1 = [1, 2, 3, 4]
var array2 = [2, 4, 5, 6]
var result = [1, 3]
I've solved the problem by looping through all the numbers in the array2 and adding them to a dictionary. Then I loop through array1 and add those that aren't in the dictionary to the result array:
var result: [Int] = []
var numbersDict: [Int : Bool] = [:]
for element in array2 {
numbersDict[element] = true
}
for element in array1 {
if numbersDict[element] == nil {
result.append(element)
}
}
I also want to find those in array2 that aren't in array1
var array1 = [1, 2, 3, 4]
var array2 = [2, 4, 5, 6]
var result = [5, 6]
I've solved this like this:
var result: [Int] = []
var numbersDict: [Int : Bool] = [:]
for element in array1 {
numbersDict[element] = true
}
for element in array2 {
if numbersDict[element] == nil {
result.append(element)
}
}
How can I do this in the most efficient way? Assuming that these arrays could potentially be tens if not hundreds of thousands of numbers long. Should I be using sorting?
Just use Set.
Example which gets elements in array1 but not in array2:
let array1: Set = [1, 2, 3, 4]
let array2: Set = [2, 4, 5, 6]
let result = array1.subtracting(array2)
print(result)
// Prints: [1, 3] <- Order may vary since it is a set
Just switch the two sets around to get the opposite result, of in array2 but not in array1.
There are lots of Set operations, another one is intersection(_:):
let result = array1.intersection(array2)
print(result)
// Prints: [2, 4] <- Again, no order
This question already has answers here:
In Swift how can I sort one array based on another array?
(4 answers)
Closed 4 years ago.
If I have:
var arrayOne = ["dog", "cat", "hamster", "horse"]
and
var arrayTwo = [3, 2, 4, 1]
How can I assign 3 to dog, 2 to cat, 4 to hamster, and 1 to horse so that if I sort arrayTwo from biggest integer to smallest, it will automatically do that for arrayOne too. In result it would print out:
var arrayOne = ["hamster", "dog", "cat", "horse"]
var arrayTwo = [4, 3, 2, 1]
What code is easiest and simplest for this?
Thanks in Advance! :)
It's quite hard to "bind" the two variables together. You could do something like this:
let dict = [3: "dog", 2: "cat", 4: "hamster", 1: "horse"]
var arrayTwo = [3, 2, 4, 1] {
willSet {
// you should probably check whether arrayTwo still has the same elements here
arrayOne = newValue.map { dict[$0]! }
}
}
It is easier to zip the arrays and then sort by arrayTwo:
let result = zip(arrayOne, arrayTwo).sorted(by: { $0.1 > $1.1 })
Now, result.map { $0.0 } is your sorted array 1 and result.map { $0.1 } is your sorted array 2.
This question already has an answer here:
Swift didSet get index of array
(1 answer)
Closed 5 years ago.
I have an array, with multiple values. I want to detect if one of those values is changed, something like this:
var array =
[
1,
2,
3,
4 { didSet{ print("Value Changed")}},
5,
6
]
Is that possible, in any way?
Thanks
Swift 3.0
You can do like below to Observer which index of array is changed.
var oldArray: [Int] = []
var array = [ 1,2,3,4,5,6] {
willSet {
// Set old array value for compare
oldArray = array
}
didSet {
let changedIndex = zip(array, oldArray).map{$0 != $1}.enumerated().filter{$1}.map{$0.0}
print("index: \(changedIndex)")
}
}
// Now change value of index 4 of array
array[4] = 10 //index: [4]
This question already has answers here:
In Swift, Array [String] slicing return type doesn't seem to be [String]
(6 answers)
Closed 5 years ago.
While try to get sub array With given Range at that time this error.
Cannot subscript a value of type '[Info]' with an index of type 'CountableRange<Int>' .
My code is
Info Modal
class Info : NSObject {
var type : Type = .Unknown
var data = ""
init() {
super.init()
}
}
Array declaration
var currentData : [Info] = []
While trying this code
let moreAnimals: [Info] = self.currentData[0..<5] //above error disply.
let currentData = [Info(), Info(), Info()]
let subarr0 = currentData[0..<2] // ArraySlice<Info>
let subarr1 = Array(currentData[0..<2]) // Array<Info>
to fetch range of element from generics collection we need to convert to NSArray and fetch the element in range using subarrayWithRange Method.
var moreAnimals: [Int] = [1,2,3,4,5,6,7,8,9,10]
var otherarr: [Int] = (moreAnimals as NSArray).subarray(with: NSMakeRange(0, 5)) as! [Int]
output ::
[1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
[1, 2, 3, 4, 5]
This question already has answers here:
How to copy end of the Array in swift?
(6 answers)
Closed 6 years ago.
How can I remove the first n elements from an array of Int in Swift?
For example:
var array = [0, 1, 2, 3, 4, 5, 6]
let n = 4
The result array contains these elements:
[4, 5, 6]
let result = Array(array.dropFirst(n))
(Thanks to KPM and WolfLink for pointing out that let result = array.dropFirst(n) sets result to an ArraySlice which will not remain valid if the original array is released.)
Slightly more succinct than Mr. Johnson's answer:
let result = array.suffix(3)
I'd still go with his because dropFirst is more intuitive / readable than suffix.
You can use a range to slice the Array:
var array = [1,2,3,4,5,6]
let n = 4
print(array[n..<array.count]) //[4,5,6]