无法为索引类型为'Int'的类型[[String:CBPeripheral]'下标

问题描述 投票:-3回答:2

我无法将单元的主标签设置为相应外围设备的名称。

帮助我找到解决方案!

image description here

var activeCentralManager: CBCentralManager?
var peripheralDevice: CBPeripheral?
var devices: Dictionary<String, CBPeripheral> = [:]
var deviceName: String?
var devicesRSSI = [NSNumber]()
var devicesServices: CBService!
var deviceCharacteristics: CBCharacteristic!  

override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return devices.count
}

func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    // Let's get a cell.
    let cell = tableView.dequeueReusableCell(withIdentifier: "cell")
    // Turn the device dictionary into an array.
    let discoveredPeripheralArray = devices as? [String : CBPeripheral]
    //println(discoveredPeripheralArray.count)

    // Set the main label of the cell to the name of the corresponding peripheral.
    if let cell = cell{
        if let name = discoveredPeripheralArray?[indexPath.row].name{
            if let textLabelText = cell.textLabel{
                textLabelText.text = name
            }
            if let detailTextLabel = cell.detailTextLabel{
                detailTextLabel.text = devicesRSSI[indexPath.row].stringValue
            }
        }
    }

    return cell!
}
swift xcode bluetooth
2个回答
1
投票

问题在这里:

// Turn the device dictionary into an array.
let discoveredPeripheralArray = devices as? [String : CBPeripheral]

[String : CBPeripheral]不是数组。这是一本字典。因此discoveredPeripheralArray也是字典。而且,您无法神奇地将字典转换为数组。


0
投票

用此替换错误行:

let discoveredPeripheralArray = devices.keys.sorted

不过,您需要确保devicesRSSI匹配相同的顺序。

© www.soinside.com 2019 - 2024. All rights reserved.