Swift无法将CBPeripheral类型的值转换为预期的参数类型

时间:2017-06-09 09:46:34

标签: objective-c swift cbperipheral

我的代码:

func didDiscoverBLE(_ peripheral: CBPeripheral!, address: String!, rssi: Int32) {


DispatchQueue.main.async(execute: {() -> Void in

                    // Handle Discovery
                    self.arrayPeripehral.contains(where:peripheral)
                        return
                    })
            self.arrayPeripehral.append(peripheral)
            let title: String = "\(peripheral.name) \(address) (RSSI:\(rssi))"
            self.arrayPeripheralName.append(title)

在这一行我有一个问题:

self.arrayPeripehral.contains(where:peripheral)
    return
})

有人有想法吗?

这是我从obective c复制到swift并且卡在这个错误上的代码

 - (void)didDiscoverBLE:(CBPeripheral *)peripheral address:(NSString *)address rssi:(int)rssi
    {
        dispatch_async(dispatch_get_main_queue(), ^{

            // Handle Discovery
            if([arrayPeripehral containsObject:peripheral])
                return;

            [arrayPeripehral addObject:peripheral];

            NSString * title = [NSString stringWithFormat:@"%@ %@ (RSSI:%d)", peripheral.name, address, rssi];

            [arrayPeripheralName addObject:title];

1 个答案:

答案 0 :(得分:1)

arrayPeripehral的类型从[CBPeripheral]更改为[Any],这将使编译器更多地了解其类型,然后使用contains(where:)这样检查数组是否包含对象。

var arrayPeripehral = [CBPeripheral]()

现在使用contains(where:)这种方式检查数组是否包含对象。

if self.arrayPeripehral.contains(where: { $0.name == peripheral.name }) {
    return
}

同时将arrayPeripheralName的{​​{1}}类型声明更改为[String],因为您只附加了[Any]个对象。

String