Given the following Objective-C class Unit
which exists in a embedded framework in my project:
@interface Unit : NSObject
// ...
@end
And Product
:
@interface Product : NSObject
@property(nonatomic, strong) NSArray<Unit *> *units;
//...
@end
The following code in my main project (which is a Swift 4 project):
extension Product {
var children: [NSObject] {
var children: [NSObject] = []
if let units = self.units {
for unit in units {
children.append(unit)
}
}
return children
}
}
Produces the following crash and error at runtime (Occurs on the for
loop line):
Could not cast value of type 'Unit_Unit_' (0x618000452930) to 'NSUnit'
(0x7fff90c579b8).
Is there a way to force the cast of the framework Unit
class in such a way as to not conflict with the NSUnit
class?
I have tried the following with no luck:
if let units = self.units as? [MyFramework.Unit] {
for unit in units { // <-- Crash occurs on this line
children.append(unit)
}
}
Am I simply out of luck and can't use Swift with this Objective-C framework due to two objects being named Unit
?
I was able to find a workaround by doing the following forced casting:
if let units = self.units {
let unitsArray: [NSObject] = (units as NSSet).allObjects as! [NSObject]
for unit in unitsArray {
children.append(unit)
}
}
Perhaps this will help someone else out!