How to update all items in Array in the correct way
You want to multply all items in the array with the double value of the text field.
A very suitable way in Swift is map
var receivedRates = [1.1, 1.6, 2.0, 1.3]
receivedRates = receivedRates.map{ $0 * Double(inputTextField.text!)! }
Alternatively you can enumerate the indices and update the values in place
receivedRates.indices.forEach{ receivedRates[$0] *= Double(inputTextField.text!)! }
I doubt that you really want to convert the text first to Int
(losing the fractional part) and then to Double
and of course you should unwrap the optionals safely.
Not able to change the value of element of array in for-loop in Swift
You might expect the loop using enumerated()
to behave the same as looping over the indices
and having let item = arr3[index]
:
for index in arr3.indices {
let item = arr3[index]
print(item)
if index+1 != arr3.count {
arr3[index + 1] += 1
}
}
However, this is not true. enumerated()
produces an EnumeratedSequence<[Int]>
. (See the source code for EnumeratedSequence
and enumerated()
). To create an EnumeratedSequence
, the original array arr3
is passed to its initialiser:
public func enumerated() -> EnumeratedSequence<Self> {
return EnumeratedSequence(_base: self)
}
As you may know, Array
is a (copy-on-write) value type. When you modify arr3
in the loop, a modified copy is created and assigned to arr3
, and the array that the EnumeratedSequence
has (i.e. the array over which the loop is iterating), is unaffected. enumerated()
is sort of creating a "snapshot" of the array at the time when you called it, so all the print(item)
will only print the old items.
Iterate through Swift array and change values
I found a simple way and would like to share it.
The key is the definition of myArray
. It would success if it's in this way:
let myArray : [NSMutableDictionary] = [["firstDict":1, "otherKey":1], ["secondDict":2, "otherKey":1], ["lastDict":2, "otherKey":1]]
myArray.enumerated().forEach{$0.element["index"] = $0.offset}
print(myArray)
[{
firstDict = 1;
index = 0;
otherKey = 1;
}, {
index = 1;
otherKey = 1;
secondDict = 2;
}, {
index = 2;
lastDict = 2;
otherKey = 1;
}]
I have two array. How Can I change different value in Array?
Not sure if that's what you are asking again. But if I understood correctly make your CountryData
conform to Equatable
, iterate your countries indices and if favCountries
contains the current element change the countries isSelected
property to true
:
extension CountryData: Equatable {
public static func ==(lhs: Self, rhs: Self) -> Bool {
lhs.name == rhs.name // match the appropriate properties
}
}
countries.indices.forEach { index in
if favCountries.contains(countries[index]) {
countries[index].isSelected = true
}
}
Change value in array in order
First zip the collection elements with their indices and sort by their elements in decreasing order.
Create rank and maxValue vars.
Create an array with exact same number of elements for storing the result.
Iterate the elements and indices.
If the element is less than maxValue minus one increase the rank value, update the maxValue and store the rank at the corresponding position of the original element at the resulting array:
let arr = [5, 55, 100, 2, 99, 100, 98]
let indexedElements = zip(arr.indices, arr).sorted(by: { $0.1 > $1.1 })
var rank = 1
var maxValue = indexedElements.first?.1 ?? .max
var result = Array(repeating: 0, count: arr.count)
for index in indexedElements.indices {
let element = indexedElements[index].1
if element < maxValue - 1 {
rank += 1
maxValue = element
}
result[indexedElements[index].0] = rank
}
print(result) // "[4, 3, 1, 5, 1, 1, 2]\n"
How to update a specific property value of all elements in array using Swift
You just need to iterate your array indices
using forEach
method and use the array index to update its element property:
struct ViewHolder {
let name: String
let age: Int
var isMarried: Bool
}
var viewHolders: [ViewHolder] = [.init(name: "Steve Jobs", age: 56, isMarried: true),
.init(name: "Tim Cook", age: 59, isMarried: true)]
viewHolders.indices.forEach {
viewHolders[$0].isMarried = false
}
viewHolders // [{name "Steve Jobs", age 56, isMarried false}, {name "Tim Cook", age 59, isMarried false}]
You can also extend MutableCollection and create a mutating method to map a specific property of your collection elements as follow:
extension MutableCollection {
mutating func mapProperty<T>(_ keyPath: WritableKeyPath<Element, T>, _ value: T) {
indices.forEach { self[$0][keyPath: keyPath] = value }
}
}
Usage:
viewHolders.mapProperty(\.isMarried, false)
viewHolders // [{name "Steve Jobs", age 56, isMarried false}, {name "Tim Cook", age 59, isMarried false}]
Find an item and change value in custom object array - Swift
Since you are using a class, use filter and first to find the value:
array.filter({$0.eventID == id}).first?.added = value
In this you:
- filter the array down to elements that match the event ID
- pick the first result, if any
- then set the value
This works since classes are pass by reference. When you edit the return value from array.filter({$0.eventID == id}).first?
, you edit the underlying value. You'll need to see the answers below if you are using a struct
EDIT: In Swift 3 you can save yourself a couple of characters
array.first({$0.eventID == id})?.added = value
EDIT: Swift 4.2:
array.first(where: { $0.eventID == id })?.added = value
array.filter {$0.eventID == id}.first?.added = value
Related Topics
Why Does the Completion Handler Does Not Return Anything
Realm Data Doesn't Show Up on a Physical Device
Uibarbuttonitem Action Not Work Uitableview Cell
How to Use the Optional Variable in a Ternary Conditional Operator
Uibutton Causing Unrecognized Selector Sent to Instance
Generate Labels and Align in Middle
Runaction on Sknode Does Not Complete
Why Is the Following Giving Me Zero
How to Change Values Inside Array Without a Loop Swift
How to Know When to Call a Closure with () or Without Parentheses in Handler:
Making Gradient Background in Swift - the Right Way
How to Give Xib Cell Button Action in Homevc in Swift
How to Simultaneously Satisfy Constraints Error Whats Causing This
Swift Optional Variable Assignment with Default Value (Double Question Marks)
Raw Value of Enumeration, Default Value of a Class/Structure, What's the Different