How to solve Fatal error: Index out of range in Xcode Swift IOS
What you can do is to remove the count of precious array ... otherwise it will try to access 3rd instance rather then 0
let cell = UITableViewCell(style: UITableViewCell.CellStyle.default, reuseIdentifier: "UserItem")
cell.textLabel?.text = contactsAry[indexPath.row - myContact.count]
Thread 1: Fatal error: Index out of range when removing from array with @Binding
In your code the ForEach
with indicies
and id: \.self
is a mistake. The ForEach
View in SwiftUI isn’t like a traditional for loop. The documentation of ForEach
states:
/// It's important that the `id` of a data element doesn't change, unless
/// SwiftUI considers the data element to have been replaced with a new data
/// element that has a new identity.
This means we cannot use indices, enumerated or a new Array in the ForEach
. The ForEach
must be on the actual array of identifiable items. This is so SwiftUI can track the row Views moving around, which is called structural identity and you can learn about it in Demystify SwiftUI WWDC 2021.
So you have to change your code to something this:
import SwiftUI
struct Item: Identifiable {
let id = UUID()
var num: Int
}
struct IntView: View {
let num: Int
var body: some View {
Text("\(num)")
}
}
struct ArrayView: View {
@State var array: [Item] = [Item(num:0), Item(num:1), Item(num:2)]
var body: some View {
ForEach(array) { item in
IntView(num: item.num)
Button(action: {
if let index = array.firstIndex(where: { $0.id == item.id }) {
array.remoteAt(index)
}
}, label: {
Text("remove")
})
}
}
}
Swift Fatal error: Index out of range (out of bounds index)
In your code trying to access 4th index due to you have used ... in loop control syntax. And 4th index not in array.
Here is some details about for swift loop.
for index in 0...4 {
...
}
The above snippet says, iterate over the range starting at 0 and inclusive of 4 i.e from 0–4
If you do not want 4 included, you use this called the half-open range operator (..<).
for index in 0..<4 {
...
}
This would loop from 0 to 3 and stop execution.
Thread 1: Fatal error: Index out of range In SwiftUI
ForEach
with an index-based approach is dangerous in SwiftUI. Instead, make your model identifiable.
class User: ObservableObject, Identifiable {
var id = UUID()
//...
Then, change your loop:
ForEach(appUser.friendAnfrage) { item in
SingleFriendView(user: item)
}
Unrelated to this exact issue, but generally SwiftUI does better with using a struct
for a model instead of a class
. If a User
in friends
is updated with your current code, because it's a nested ObservableObject
, your View
will not get automatically updated.
Swift 5 Thread 1: Fatal error: Index out of range
The problem with stride(from:through:by:)
is that it includes that final value supplied to through
. Consider:
let strings = ["foo", "bar", "baz"]
for index in stride(from: 0, through: strings.count, by: 1) {
print(index)
}
That will print four values (!):
0
1
2
3
If you tried to use that index as a subscript in the array ...
for index in stride(from: 0, through: strings.count, by: 1) {
print(index, strings[index])
}
... it would work for the first three indexes, but that fourth one would fail because there are only three items in the array:
0 foo
1 bar
2 baz
Fatal error: Index out of range
You could solve this by using to
, instead, striding up to, but not including, that final value:
for index in stride(from: 0, to: strings.count, by: 1) {
print(index, strings[index])
}
That would stop at the third entry, and everything would be good:
0 foo
1 bar
2 baz
All of that having been said, we wouldn’t generally use stride
at all with a by
value of 1. We’d just use a half-open range operator, ..<
:
for index in 0 ..< strings.count {
print(strings[index])
}
Or, better, you might instead use:
for index in strings.startIndex ..< strings.endIndex {
print(strings[index])
}
Or, better, use indices
:
for index in strings.indices {
print(strings[index])
}
The use of indices
becomes essential if you happen to be working with slices of arrays, where one cannot assume the appropriate values, or if you happen to be dealing with some random access collection that does not happen to use numeric indices.
Or, since you don’t really need that index, you would just do:
for string in strings {
print(string)
}
Or, in your case:
for post in posts {
let url = URL(string: "https://api.tdameritrade.com/v1/marketdata/\(post.symbol)/quotes")!
...
}
Related Topics
Create View Based Nstableview Programmatically Using Bindings in Swift
Swift Protocol to Require Properties as Protocol
Nested Types in Swift - What Is the Good Practice
Launch Sudo Command from MACos App Swift
Uibarbuttonitem Selector Not Working
Arkit -Drop a Shadow of 3D Object on the Plane Surface
Programatic Constraints Not Obeyed
How to Find Max Value for Double and Float in Swift
Appearance Proxies/Ui_Appearance_Selector in Swift
Lazy Property Initialization in Swift
Swift Operator "*" Throwing Error on Two Ints
Nsdata Contentsofurl Constructor Returns Nil
What Happens When You Run Deprecated Code in Swift