该解决方案帮助我避免空数组,但不能让我提取数组[0]旁边的值
在将所有值附加到数组后,我想提取2个值
array[0]打印成功,但错误消息显示为";索引超出范围";当我试图打印出数组1时。
下面是代码:
var followingList = [User]()
func fetchfollowingList(callback: @escaping ([User]) -> Void) {
API.User.fetchFollowingList { followingUser in
self.followingList.append(followingUser)
callback(self.followingList)
print(self.followingList)
}
print(self.followingList[0].displayName)
print(self.followingList[1].displayName)
}
";print(self.followingList(";控制台中的结果:
[APP01.User]
[APP01.User, APP01.User]
[APP01.User, APP01.User, APP01.User]
我推断数组1是从只附加了一个值的第一个数组中提取的,而不是从附加了所有值的第三个数组中提取的并且不知道如何修复它
感谢
填充数组的函数是async
函数,因此当编译器达到print
状态时,它可能还没有被填充。因此,您也应该异步检查。类似于:
func fetchfollowingList(callback: @escaping ([User]) -> Void) {
API.User.fetchFollowingList { followingUser in
self.followingList.append(followingUser)
callback(self.followingList)
print(self.followingList)
self.printIfNeeded() // <- Check everytime something appended
}
}
func printIfNeeded() {
guard followingList.count > 1 else { return } // Check the condition you need.
print(self.followingList[0].displayName)
print(self.followingList[1].displayName)
}