ios - 在惰性 var 属性中调用异步函数

标签 ios swift

有没有办法从惰性或计算属性调用异步函数?

struct Item {
  lazy var name: String = {
    API.requestThing({ (string: String) in // Xcode didn't like this
      return string // this would not work here
    })
  }()
}

class API {
  class func requestThing(completion: String -> Void) {
    completion("string")
  }
}

最佳答案

API.requestThing 中的完成处理程序返回一个字符串,但它应该没有返回值:

(completion: String -> Void)

我让这个工作:

struct Item {
    lazy var name: String = {
        API.requestThing({ (string: String) in 
            return string
        })
    }()
}

class API {
    class func requestThing(completion: String -> String) -> String {
        return completion("string")
    }
}

关于ios - 在惰性 var 属性中调用异步函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36379619/

相关文章:

objective-c - 是否有合法的方式从我的应用程序中获取 iOS 设备上所有已安装的应用程序?

swift - 从当前位置到注释的距离。 (火力基地)

ios - 搜索栏 - 导航栏中的取消按钮

ios - iOS像Homido App一样并排播放同一视频

ios - 为什么 SwiftUI View 模型应该用 @MainActor 注释?

swift - 从 .plist 读取总是返回 nil

ios - 另一种解决方案而不是 tableView.reloadData()

css - 我们如何在 ios 9 的 uiwebview 中禁用放大镜 - Swift

ios - 长按 UIButton

ios - 如何将referencenode转换为GameScene坐标?