I am migrating my iOS project to Swift. I am doing this class by class. When I call Objective C methods from Swift, a lot of Objective C types are converted to their Swift counterparts.
In my case an Objective C NSMutableArray
gets converted to Swift's Array<AnyObject>
. Now here comes my problem. Within my Swift class, I get such an array back from an Objective C object. Now that I am in the Swift world, I would like to cast this array to a specific type instead of AnyObject
, because I know for sure what kind of objects exist in this array.
The compiler won't let me do that! Let me simplify my problem by saying I want to cast to an array containing strings. This is what I tried:
var strings = myObjcObject.getStrings() as [String]
I get the following error from the compiler:
'String' is not identical to 'AnyObject'
I would have to agree with the compiler, since String is indeed not identical to AnyObject. But I don't see why that is a problem. I can downcast AnyObject to String if I want, right?
I also tried:
var strings = myObjcObject.getStrings() as? [String]
This seems to be a step in the right direction, but getStrings() returns an NSMutableArray
so I get the following error:
'NSArray' is not a subtype of 'NSMutableArray'
Is there any way to do what I am trying to do here?
See Question&Answers more detail:
os 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…