Swift 5线程1:致命错误:索引超出范围

时间:2020-03-22 04:25:21

标签: swift swift5

我正在使用数组计数遍历一个数组。该代码将运行一次,然后,我得到索引超出范围错误。我的代码如下。我不知道为什么会出现此错误。有人可以让我知道我在想什么吗?

for stockItem in stride(from: 0, through: self.posts.count, by: 1) {


            guard let url = URL(string: "https://api.tdameritrade.com/v1/marketdata/\(self.posts[stockItem].symbol)/quotes") else {
                print("URL does not work")
                fatalError("URL does not work!")

            }}

2 个答案:

答案 0 :(得分:2)

stride(from:through:by:)的问题在于它包括提供给through的最终值。考虑:

let strings = ["foo", "bar", "baz"]
for index in stride(from: 0, through: strings.count, by: 1) {
    print(index)
}

这将打印四个值(!):

0
1
2
3 

如果您尝试使用该索引作为数组中的下标...

for index in stride(from: 0, through: strings.count, by: 1) {
    print(index, strings[index])
}

...它适用于前三个索引,但是第四个索引将失败,因为数组中只有三个项目:

0 foo
1 bar
2 baz
Fatal error: Index out of range 

您可以使用to来解决此问题,而不是逐步增加但不包括最终值:

for index in stride(from: 0, to: strings.count, by: 1) {
    print(index, strings[index])
}

那会停在第三项,一切都会很好:

0 foo
1 bar
2 baz

所有这些,我们通常不会使用stride值为1的by。我们只会使用half-open range operator,{{1} }:

..<

或者,因为您实际上并不需要该索引,所以只需这样做:

for index in 0 ..< strings.count {
    print(strings[index])
}

或者,就您而言:

for string in strings {
    print(string)
}

答案 1 :(得分:0)

您使用了through而不是to

但是没有理由大步向前!进行更有意义的迭代,可以更好地避免此问题。