swift - Objc - Swift 互操作性 : Objc API for Any type?

标签 swift

我有一个像这样定义的 objective-c API:

- (instancetype)initWithItems:(NSArray *)items reuseIdentifier:(NSString *)reuseIdentifier configuration:(void(^)(id item, id cell, NSIndexPath *indexPath))configuration;

这转化成 Swift 是这样的:

public init!(items: [AnyObject]!, reuseIdentifier: String!, configuration: ((AnyObject!, AnyObject!, NSIndexPath!) -> Void)!)

现在,我想将此 API 与 swift 结构数组一起使用,但遗憾的是我无法将结构转换为 AnyObject。有什么方法可以编写一个带有 id 类型的 Objc API,该类型转换为 swift 类型 Any 以便我可以同时使用 swift 类和结构?

最佳答案

这是不可能的,因为 NSArray只能存储AnyObject因为它们都具有相同的大小(1 个指针)。另一方面,结构具有可变大小(Bool 有 1 个字节,Int16 2 个字节,等等)。

Swift 3 接受提案 Import Objective-C id as Swift Any type可能会使这成为可能:

Untyped Cocoa collections come in as collections of Any. NSArray imports as [Any]

您现在可以编写一个简单的类包装器:

struct MyStruct {
    let a : Int
    let b : Int
}

final class Box : NSObject {
    let value : MyStruct
    init(value: MyStruct) {
        self.value = value
    }
}

let x = MyStruct(a: 1, b: 2)

let object : AnyObject = Box(value: x)

您必须自己测试它是否适用于 ObjC,尤其是如何访问结构属性,因为我对此没有任何经验。

编辑:您可以使用 Lightweight Generics在 Objective-C 中,这样 NSArray<Box *>作为 [Box] 导入到 Swift 中

关于swift - Objc - Swift 互操作性 : Objc API for Any type?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38537553/

相关文章:

ios - 界面测试失败 : Multiple Matches Found Error

swift - 使用核心数据进行本地化

ios - 快速手势识别器 longpress with pinch and drag

ios - Swift 中类型的静态属性

ios - 由于 textView 无法选择 tableView Cell

ios - WKWebView 链接不工作

ios - imageView 下的空白区域

swift - swift 中的类型协议(protocol)数组

swift - 测试模块时重置单例状态

ios - 在 RxSwift 的 UICollectionViewCell 中订阅 UIButton 点击​​?