【问题标题】:Use Objective-C blocks in swift快速使用 Objective-C 块
【发布时间】:2017-03-20 12:42:03
【问题描述】:

我的 swift 项目中有一个第三方 Objective-C 库,在其中一个 .h 文件中,它有一个 typedef:

typedef void (^YDBlutoothToolContectedList) (NSArray *);

在类内部,它有一个属性:

@property (nonatomic, copy) YDBlutoothToolContectedList blutoothToolContectedList;

(请忽略其拼写)

当我尝试在我的 swift 类中使用此属性时,我使用

bt.blutoothToolContectedList = {(_ tempArray: [Any]) -> Void in
    self.devices = tempArray
    self.tableView.reloadData()
}

我得到错误说:

Cannot assign value of type '([Any]) -> Void' to type 'YDBlutoothToolContectedList!'

我知道上面的 swift 中的 Objective-C 代码是:

typealias YDBlutoothToolContectedList = () -> Void

但是我不能重写那个Objective-C文件并且swift不能强制转换闭包类型,有没有办法解决这个问题?

【问题讨论】:

    标签: ios objective-c swift closures objective-c-blocks


    【解决方案1】:
    typedef void (^YDBlutoothToolContectedList) (NSArray *);
    

    映射到 Swift 为

    public typealias YDBlutoothToolContectedList = ([Any]?) -> Swift.Void
    

    因为闭包参数可以是nil。 (您可以验证 通过选择 .h 文件,然后在 Xcode 菜单中选择 Navigate->Jump to Generated Interface。)

    因此 正确的分配是

    bt.blutoothToolContectedList = {(_ tempArray: [Any]?) -> Void in
        // ...
    }
    

    或者干脆让编译器推断参数类型:

    bt.blutoothToolContectedList = { tmpArray in
        // ...
    }
    

    如果您可以在 Objective-C 定义中添加可空性注释:

    typedef void (^YDBlutoothToolContectedList) (NSArray  * _Nonnull );
    

    然后它将被映射到 Swift

    public typealias YDBlutoothToolContectedList = ([Any]) -> Swift.Void
    

    【讨论】:

    • 谢谢!我没有太多的 OC 经验,所以有时我很难阅读一些 OC 源代码并尝试将它们转换为 Swift。
    • @SensEyeNULL:不客气!这回答了你的问题了吗?如果您需要更多信息,请告诉我。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-09-23
    • 2012-03-22
    • 1970-01-01
    相关资源
    最近更新 更多