Oleksandr Matrosov
Oleksandr Matrosov

Reputation: 27123

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]

Upvotes: 1

Views: 596

Answers (2)

Nirav D
Nirav D

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

Kirit Modi
Kirit Modi

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

Related Questions