簡體   English   中英

結合使用NSMutableArray和[Swift Array]

[英]Combine NSMutableArray with [Swift Array]

目標:我想擁有一個可計算的屬性,該屬性基於NSMutableArray和swift數組組合返回具有不同類型對象的數組。

這里有兩個問題:

  1. 計算屬性包含帶有NSMutableArray代碼
  2. 我不知道如何合並兩個數組。 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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM