Reputation: 269
Here I am just getting array count and using for loop but got crashed at let arr = arrayAdaptor[i]
this line after completing my array count don't know why it's crashing can anyone help me how to resolve this
var arrayAdaptor = [Struct_Row_Rating]()
for i in 0...arrayAdaptor.count {
let arr = arrayAdaptor[i]
let number = arr.row
let row = number + 1
dict.updateValue("\(arr.rating)", forKey: "\(row)")
print(dict)
}
struct Struct_Row_Rating {
var row: Int
var rating: Double
init(row: Int , rating: Double) {
self.row = row
self.rating = rating
}}
Upvotes: 1
Views: 852
Reputation: 91
You can also iterate loop by 'map' function:
let _ = arrayAdaptor.map({ adaptor in
let number = adaptor.row
let row = number + 1
dict.updateValue("\(adaptor.rating)", forKey: "\(row)")
print(dict)
})
Upvotes: 0
Reputation: 3657
Why you are using 0...arrayAdaptor.count
range style avoid it and Simply Use enumerated() of an Array:
for (_,value) in arrayAdaptor.enumerated() {
let number = value.row
let row = number + 1
dict.updateValue("\(arr.rating)", forKey: "\(row)")
print(dict)
}
If you don't want any index to try with this:
for value in arrayAdaptor {
let number = value.row
let row = number + 1
dict.updateValue("\(arr.rating)", forKey: "\(row)")
print(dict)
}
Upvotes: 6
Reputation: 14329
From Swift 4 you can use One sided ranges.
i...
is favored over i..<
because the latter is ugly. We have to pick one, two would be redundant and likely to cause confusion over which is the "right" one. Either would be reasonable on pedantic correctness grounds – (i as Int)...
includes Int.max consistent with ...,
whereas a[i...]
is interpreted as a[i..<a.endIndex]
consistent with i..<.
Example:
var names = ["Jack", "New", "peter"]
let first = names[0...]
let second = names[..<names.count]
print(first)//prints ["Jack", "New", "peter"]
print(second)//prints ["Jack", "New", "peter"]
Upvotes: 1
Reputation: 6058
One of the options not mentioned in the answers is forEach
approach.
arrayAdaptor.forEach { item in
print(item)
}
or
arrayAdaptor.forEach {
print($0) // without named parameter
}
// Your case:
arrayAdaptor.forEach { item in
let arr = item
let number = item.row
let row = number + 1
dict.updateValue("\(arr.rating)", forKey: "\(row)")
print(dict)
}
This is pretty much the same as the handy for..in
mentioned in vadian's answer:
for arr in arrayAdaptor { ... }
Upvotes: 1
Reputation: 285072
The operator ...
exceeds the range of the array. You have to write
for i in 0..<arrayAdaptor.count
or
for i in 0...arrayAdaptor.count - 1
Basically don't use these index based for
loops in Swift at all.
Use Fast Enumeration
:
for arr in arrayAdaptor {
and if you really need the index
for (index, arr) in arrayAdaptor.enumerated() {
Upvotes: 8