[英]Combine NSMutableArray with [Swift Array]
目標:我想擁有一個可計算的屬性,該屬性基於NSMutableArray
和swift數組組合返回具有不同類型對象的數組。
這里有兩個問題:
NSMutableArray
代碼 NSMutableArray
+ [AnyObjct]
我有一個Objective-C類CentralManager
,其類中的方法storedDevices
返回帶有某些對象的NSMutableArray
。 例:
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
}
}
另外,當我使用swift時,不確定我的計算屬性是否應返回NSMutableArray
,也許最好返回[AnyObject]
您可以addObjectsFromArray
使用NSMutableArray
addObjectsFromArray
方法
var allDevices: NSMutableArray {
get {
var blueToothDevices = CentralManager.shared().storedDevices
let devices = blueToothDevices.addObjectsFromArray(wifiDevices)
return devices
}
}
編輯:如果您希望allDevices
為swift數組,並且blueToothDevices
包含對象的WifiDevice
類型,則可以像這樣使用[WifiDevice]
。
var blueToothDevices = CentralManager.shared().storedDevices
var devices = blueToothDevices.objectEnumerator().allObjects as! [WifiDevice]
let devices = devices + wifiDevices
對於任何物體
var allDevices: [AnyObject] {
get {
var blueToothDevices = CentralManager.shared().storedDevices
var blueTooths = blueToothDevices.objectEnumerator().allObjects
blueTooths = blueTooths + wifiDevices
return blueTooths
}
}
讓我們看一個簡單的例子:
NSMutableArray
取一個帶有兩個對象“ A”和“ B”的NSMutableArray
let mutableArray = NSMutableArray()
mutableArray.addObject("A")
mutableArray.addObject("B")
print(mutableArray)
Swift數組:
帶兩個對象“ C”和“ D”的Swift Array
var swiftArray = [String]()
swiftArray = ["C" , "D"]
連接兩個數組
let mutableSwift = mutableArray.objectEnumerator().allObjects as? [String]
swiftArray = swiftArray + mutableSwift!
print(swiftArray)
終於你迅速數組
[“ C”,“ D”,“ A”,“ B”]
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.