Reputation: 27123
The goal:
I want to have a computed property which returns an array with different type of objects based on NSMutableArray
and swift array combination.
Two problem here:
NSMutableArray
NSMutableArray
+ [AnyObjct]
I have an Objective-C class CentralManager
with a method storedDevices
that returns NSMutableArray
with some objects. Example:
var wifiDevices = [WifiDevice]()
var allDevices: NSMutableArray {
get {
let blueToothDevices = CentralManager.shared().storedDevices
let devices = blueToothDevices + wifiDevices // it does not work as we can't combine NSMutableArray and swift array.
return devices
}
}
Also as I use swift not sure that my computed property should return NSMutableArray
, maybe it's better to return [AnyObject]
Upvotes: 1
Views: 596
Reputation: 72410
You can use addObjectsFromArray
method of NSMutableArray
for that
var allDevices: NSMutableArray {
get {
var blueToothDevices = CentralManager.shared().storedDevices
let devices = blueToothDevices.addObjectsFromArray(wifiDevices)
return devices
}
}
Edit: If you want allDevices
to be of swift array and your blueToothDevices
contains WifiDevice
type of object you can use [WifiDevice]
like this way.
var blueToothDevices = CentralManager.shared().storedDevices
var devices = blueToothDevices.objectEnumerator().allObjects as! [WifiDevice]
let devices = devices + wifiDevices
For Any Object
var allDevices: [AnyObject] {
get {
var blueToothDevices = CentralManager.shared().storedDevices
var blueTooths = blueToothDevices.objectEnumerator().allObjects
blueTooths = blueTooths + wifiDevices
return blueTooths
}
}
Upvotes: 1
Reputation: 23407
Let's See Simple Example :
NSMutableArray
Take one NSMutableArray
with two Object "A" and "B"
let mutableArray = NSMutableArray()
mutableArray.addObject("A")
mutableArray.addObject("B")
print(mutableArray)
Swift Array :
Take Swift Array with two Object "C" and "D"
var swiftArray = [String]()
swiftArray = ["C" , "D"]
concat two Array
let mutableSwift = mutableArray.objectEnumerator().allObjects as? [String]
swiftArray = swiftArray + mutableSwift!
print(swiftArray)
Finally You Swift Array
["C", "D", "A", "B"]
Upvotes: 0