简体   繁体   中英

Swift: Why can't I use 'contains(: )"?

Step 1: I declared a protocol, named ARDevice :

protocol ARDevice {
    var deviceName:String{get}
}

Step 2: Then I used it to extend NSNetService

extension NSNetService:ARDevice{
    var deviceName:String{
       get{
           return self.name
       }
    }
}

Step 3: I created an array:

var deviceList = [ARDevice]()

Step 4: I want to use contains(:) in a call back method, but I can't: 在此输入图像描述

How can I do that? Am I have to implement any protocol?

 if !deviceList.contains(service) { }

can only be used if the elements of the deviceList array – in your case ARDevice – conform to the Equatable protocol. In particular, a == operator must be defined for them.

The easiest solution here is to use the "predicate-based" contains() method:

if  !deviceList.contains ({ $0.deviceName == service.deviceName }) {
    deviceList.append(service)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM