ios - 具有异步闭包变量的结构函数

标签 ios swift asynchronous closures

我正在尝试做某事可能很奇怪,但我遇到了以下问题。

我有一个带有闭包属性的结构,我设置了异步函数。

我想要的是,调用这个异步函数来获取返回值。

我可以使用变通解决方案来解决这个问题,但我想以正确的方式来解决。

感谢任何帮助。

这是我的代码:

struct Item {
  var myselector: (String -> Void)?
  func getMeThat(completion: String -> Void) {
    completion(myselector()) // error: cannot call value of non-function type String -> Void
  }
}

class API {
  class func requestThing(completion: String -> Void) {
    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
      completion("Kenan")
    })
  }
}

class ViewController {
  func viewDidLoad() {
    var item = Item()
    item.myselector = { // error: cannot assign value of type () -> () to type String -> Void
      API.requestThing({ (str: String) in
        <#code#>
      })
    }
    item.getMeThat({ (rtn: String) in
      print(rtn)
    })
  }
}

最佳答案

主要问题是由于奇怪的重复导致您与签名的不匹配。

您将闭包设置为结构的变量,但也为函数提供了完成。做一个或另一个。

struct Item {
    func getMeThat(completion: String -> Void) {
        API.requestThing(completion)
    }
}

class API {
    class func requestThing(completion: String -> Void) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
            completion("Kenan")
        })
    }
}

class ViewController {
    func viewDidLoad() {
        let item = Item()
        item.getMeThat({ (rtn: String) in
            print(rtn)
        })
    }
}

如果你只是想延迟代码的执行,这就是你的做法

struct Item {
    var myselector: (Void -> Void)?
    func executeSelector() {
        guard let sel = myselector else {
            return
        }

        sel()
    }
}

class API {
    class func requestThing(completion: String -> Void) {
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, Int64(2 * Double(NSEC_PER_SEC))), dispatch_get_main_queue(), {
            completion("Kenan")
        })
    }
}

class ViewController {
    func viewDidLoad() {
        var item = Item()
        item.myselector = {
            API.requestThing({ (str: String) in
                print(str)
            })
        }
        item.executeSelector()
    }
}

关于ios - 具有异步闭包变量的结构函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36378939/

相关文章:

ios - iOS 是否会在应用程序启动时将所有系统动态框架加载到内存中?

swift - 闭包存储属性初始化有什么好处?

validation - Angular2 模板驱动的异步验证器

ios - 在 Swift 的 Singleton 类中防止实例来自 init() 的最佳实践是什么

swift - Action 完成后做一些事情

javascript - 异步函数调用中的共享变量

wcf - 如何检测等待的异步 wcf 调用?

ios - 我怎么知道是否选择了 UITableView 的单元格?

ios - 使用 CBPeripheralManager 构建 iBeacon

javascript - 在 iOS 和 OSX 上的强制网络助手 (WISPr) 中运行 angularJS