Arrays 将所有值注入数组后,如何从数组中提取值?

Arrays 将所有值注入数组后,如何从数组中提取值?,arrays,swift,xcode,Arrays,Swift,Xcode,帮助我避免使用空数组,但不能提取数组[0]旁边的值。 将所有值附加到数组后,我想提取2个值。 数组[0]已成功打印,但在我尝试打印数组时,错误消息显示为“索引超出范围” 代码如下: var followingList = [User]() func fetchfollowingList(callback: @escaping ([User]) -> Void) { API.User.fetchFollowingList { followingUser i

帮助我避免使用空数组,但不能提取数组[0]旁边的值。
将所有值附加到数组后,我想提取2个值。
数组[0]已成功打印,但在我尝试打印数组时,错误消息显示为“索引超出范围”

代码如下:

    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)
    }
控制台中的“打印(自我跟踪列表)”结果:

[APP01.User]  
[APP01.User, APP01.User]   
[APP01.User, APP01.User, APP01.User]
我推断数组是从只附加了一个值的第一个数组中提取出来的,而不是从附加了所有值的第三个数组中提取出来的,并且不知道如何修复它


谢谢

填充数组的函数是一个
异步
函数,因此当编译器达到
打印
状态时,它可能还没有被填充。所以你也应该异步地检查它。比如:

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)
}
func fetchfollowList(回调:@escaping([User])->Void){
API.User.fetchFollowList{followUser in
self.followList.append(followUser)
回调(self.followList)
打印(自我跟踪列表)
self.printifRequired()//1 else{return}//检查所需的条件。
打印(self.followList[0].displayName)
打印(self.followList[1].displayName)
}

这是否回答了您的问题?。您已经问过这个问题,并且得到了这个问题的答案。请帮助我避免使用空数组,但不能让我提取数组[0]之外的值。非常感谢您的回答,它确实有效。但是,请让我进一步解释为什么访问附加了所有值的数组对我很重要:我需要调用shuffled()方法并从数组中提取2个值。打印(数组[1])是验证数组中是否有多个值的方法之一。“未来与承诺”虽然我一直在调查这个问题,但可能会有所帮助,但对我来说仍然很难理解。欢迎使用您的任何示例代码来解决这个问题。有多种解决方案。但是您可能需要考虑一下,如果您没有找到任何解决方案,请使用嵌入的试用代码问另一个问题。然后我可以帮助您解决这个问题,我的朋友.