'didSet' certain elements inside Arrays - Swift [duplicate] - ios

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]

Related

Function and array of strings using swift [duplicate]

This question already has answers here:
How to sort array of strings by length in reverse/descending order in Swift?
(2 answers)
Closed last year.
Good day everyone I want to create a function that takes an array of strings and return an array, sorted from shortest to longest but I'm getting a terminated by signal 4 error. I'm using an online swift compiler on my windows laptop if that somehow matters.
here's the code I wrote:
var siliconvalley = ["Google", "Apple", "Microsoft"]
var elementamount: Int = siliconvalley.count
var newarray: [String] = [] //new array created to store the newly sorted array
var a = siliconvalley[0].count // this variable was created to count the letters of the first string in the array
var temporary: String = "" // this was created to store the largest string so that I can use it to append the new array
func longestelement () -> [String] {
repeat {
if siliconvalley[1].count > a {
print (siliconvalley[1])
temporary = siliconvalley[1]
siliconvalley.remove(at:1)
}
else if siliconvalley[2].count > a {
print (siliconvalley[2])
temporary = siliconvalley[2]
siliconvalley.remove(at:2)
}
else {
print (siliconvalley[0])
temporary = siliconvalley[0]
siliconvalley.remove(at:0)
}
newarray.append(temporary)
elementamount = elementamount - 1
} while elementamount > 0
return newarray
}
print (longestelement())
You know swift has built-in sorting? You can do:
siliconvalley.sorted(by: {$0.count < $1.count})
and then if you just want the longest use .last
here's the issue:
while elementamount > 0
Consider rechecking the code for possible illogical loop termination condition.
P.S: elementamount is always greater than 0.

How can I change the order of two arrays when one array is sorted? [duplicate]

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.

Sort an array on three variables [duplicate]

This question already has answers here:
Swift - Sort array of objects with multiple criteria
(8 answers)
Closed 5 years ago.
I have an array with playing cards. I would like to sort these on value, color and playability.
I have 4 colors; 1, 2, 3, 4.
I have 3 playability options; 1, 2, 3.
I have 5 values; 1, 2, 3, 4, 5.
I am able to sort the array on color and value. So if the color is the same, the array is sorted on value.
example color-value pairs:
1-2, 1-4, 1-5, 2-2, 3-1, 3-2, 3-5
Code is,
playerCards.sort {
if $0.colorSorter == $1.colorSorter {
return $0.value < $1.value
}
return $0.colorSorter < $1.colorSorter
}
How do I add the third paramater to sort on playability additionally?
What I would like to see (playability-color-value triplets):
1-1-2, 1-1-4, 1-2-2, 1-3-1, 2-1-5, 2-3-1, 2-3-2, 3-3-5
1: sort on playability
2: sort on color
3: sort on value.
Thanks!
Assuming this is your struct
struct Card {
let color:Int
let value:Int
let playability:Int
}
and this is your array
let cards:[Card] = ...
You can sort cards by
playability
color
value
writing
let sorted = cards.sorted { (left, right) -> Bool in
guard left.playability == right.playability else { return left.playability < right.playability }
guard left.color == right.color else { return left.color < right.color }
return left.value < right.value
}

Try to get sub array With given Range [duplicate]

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]

How to remove item in Array? [duplicate]

This question already has answers here:
RemoveAtIndex crash from swift array
(5 answers)
Closed 6 years ago.
I am coding with Swift, and confuse with one problem.
I encountered Index out of Range Error when I am trying to remove one item from array during the array's enumeration.
Here is my error codes:
var array :[Int] = [0,1,2,3,4,5]
for (index, number) in array.enumerate() {
if array[index] == 2 {
array.removeAtIndex(index) // Fatal error: Index out of range
}
}
Does that means array.enumerate() not be called during each for loop?
I have to change my codes like that:
for number in array {
if number == 2 || number == 5 {
array.removeAtIndex(array.indexOf(number)!)
}
}
Or
var index = 0
repeat {
if array[index] == 2 || array[index] == 4 {
array.removeAtIndex(index)
}
index += 1
} while(index < array.count)
You are removing item at the same time when you are enumerating same array. Use filter instead:
var array: [Int] = [0,1,2,3,4,5]
array = array.filter{$0 != 2}
or, for multiple values, use Set:
let unwantedValues: Set<Int> = [2, 4, 5]
array = array.filter{!unwantedValues.contains($0)}
Same in one line:
array = array.filter{!Set([2, 4, 5]).contains($0)}

Resources