我想获取api以从惰性var中的服务器获取内容。以下是我的代码,我不确定如何使它工作。有什么线索吗?我知道我们无法从完成处理程序返回,所以我在这里迷路了。不知道还有什么其他方法可以做到这一点?

private(set) lazy var orderedViewControllers: [UIViewController] = {
        self.fetchPages()
    }()

func fetchPages() -> [UIViewController] {
    fetchIntroPages() { (result, error) in
        if error != nil {
        } else {
            if result?.data != nil {
                if (result?.success)! {
                    var newColoredViewControllerArray: [UIViewController] = []
                    for page in result!.data! {
                        newColoredViewControllerArray.append(self.newColoredViewController(pageId: page.id!, pageTitle: page.title!, pageContent: page.content!))
                    }
                    // This will not work
                    return newColoredViewControllerArray
                }
            } else {
            }
        }
    }
}

最佳答案

首先,在进行异步调用时,不要返回结果,而应使用完成处理程序

func fetchPages(_ completion: @escaping ([UIViewController]?) -> ()) {

    fetchIntroPages() { result, error in
        ...
            if let result = result {
                if result.success {
                    ...
                    completion(newColoredViewControllerArray)
                    return
                }
            }
        }
        completion(nil)
    }

}


那么请不要使用lazy变量,因为您正在进行异步调用,因此无法提供返回值。如果需要,仅使用“普通”存储变量

var orderedViewControllers: [UIViewController]?


现在,在需要的地方调用fetchPages并在其完成闭包中分配变量

fetchPages { viewControllers in
    if let viewControllers = viewControllers { // if you don't want to change controllers if there was any error
        self.orderedViewControllers = viewControllers
        ... // moment when you have `orderedViewControllers`
    }
}

08-05 07:29
查看更多