我的代码:
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];
答案 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