How can I cast an NSMutableArray to a Swift array of a specific type?
You can make this work with a double downcast, first to NSArray
, then to [String]
:
var strings = myObjcObject.getStrings() as NSArray as [String]
Tested in a Playground with:
import Foundation
var objCMutableArray = NSMutableArray(array: ["a", "b", "c"])
var swiftArray = objCMutableArray as NSArray as [String]
Update:
In later versions of Swift (at least 1.2), the compiler will complain about as [String]
. Instead you should use an if let
with a conditional downcast as?
:
import Foundation
var objCMutableArray = NSMutableArray(array: ["a", "b", "c"])
if let swiftArray = objCMutableArray as NSArray as? [String] {
// Use swiftArray here
}
If you are absolutely sure that your NSMutableArray
can be cast to [String]
, then you can use as!
instead (but you probably shouldn't use this in most cases):
import Foundation
var objCMutableArray = NSMutableArray(array: ["a", "b", "c"])
var swiftArray = objCMutableArray as NSArray as! [String]
compactMap
is your friend in Swift 4.1 and above, as well as in Swift 3.3-3.4 for that matter. This means that you don't have any double or forced casting.
let mutableArray = NSMutableArray(array: ["a", "b", "c"])
let swiftArray: [String] = mutableArray.compactMap { $0 as? String }
In previous versions of Swift, 2.0-3.2 and 4.0, you'll want to use flatMap
for this purpose. The usage is the same as compactMap
:
let swiftArray: [String] = mutableArray.flatMap { $0 as? String }
With Swift 1.2 the following will work:
let mutableArray = NSMutableArray(array: ["a", "b", "c"])
let swiftArray = NSArray(array: mutableArray) as? [String]