简体   繁体   English

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

[英]How to extract values from the array after all values are injected into the array?

The solution help me avoid the empty array but can't let me extract values beside array[0]. 该解决方案帮助我避免空数组,但不能让我提取数组 [0] 旁边的值。
I'd like to extract 2 values after appending all values to the array.我想在将所有值附加到数组后提取 2 个值。
array[0] is printed out successfully but the error message appeared as "Index out of range" while I tried to print out array 1 . array[0] 已成功打印,但当我尝试打印 array 1 时,错误消息显示为“索引超出范围”。

below is the code:下面是代码:

    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)
    }

the "print(self.followingList)" result in console:控制台中的“打印(self.followingList)”结果:

[APP01.User]  
[APP01.User, APP01.User]   
[APP01.User, APP01.User, APP01.User]

I inferred that the array 1 is being extracted from the 1st array appended with only one value instead of the 3rd array appended with all values and not knowing how to fix it.我推断数组1是从仅附加一个值的第一个数组中提取的,而不是附加了所有值且不知道如何修复它的第三个数组

thanks谢谢

The function that fills the array is an async one, so when the compiler reaches the print state, it may not be filled yet .填充所述阵列是功能async之一,所以当编译器到达print状态时,它可能尚未填充。 So you should check for that asynchronously too.所以你也应该异步检查。 Something like:就像是:

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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM