防止 Obj-C 框架 class 与 Swift 中的 NSUnit 命名冲突

Prevent Obj-C framework class naming conflict with NSUnit in Swift

鉴于以下 Objective-C class Unit 存在于我项目的嵌入式框架中:

@interface Unit : NSObject

// ...

@end

Product

@interface Product : NSObject

@property(nonatomic, strong) NSArray<Unit *> *units;

//...

@end

我的主项目(这是一个 Swift 4 项目)中的以下代码:

extension Product {

    var children: [NSObject] {
        var children: [NSObject] = []

        if let units = self.units {
            for unit in units {
                children.append(unit)
            }
        }

        return children
    }

}

在运行时产生以下崩溃和错误(发生在 for 循环行):

Could not cast value of type 'Unit_Unit_' (0x618000452930) to 'NSUnit'
(0x7fff90c579b8).

有没有办法以不与 NSUnit class 冲突的方式强制转换框架 Unit class?

我试过以下但没有成功:

if let units = self.units as? [MyFramework.Unit] {
    for unit in units { // <-- Crash occurs on this line
        children.append(unit)
    }
}

我是不是运气不好,因为有两个对象被命名为 Unit,所以无法将 Swift 与此 Objective-C 框架一起使用?

我能够通过执行以下强制转换找到解决方法:

if let units = self.units {
    let unitsArray: [NSObject] = (units as NSSet).allObjects as! [NSObject]
    for unit in unitsArray {
        children.append(unit)
    }
}

也许这会对其他人有所帮助!