Matrosov Alexander Matrosov Alexander - 3 months ago 20
Objective-C Question

Combine NSMutableArray with [Swift Array]

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:


  1. Computed property contains code with an
    NSMutableArray

  2. I don't know how to combine two arrays.
    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]

Answer

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
    }
}