0

Here's my setup:

protocol Client {
    var identifier: NSUUID { get }
}

class PeripheralClient: NSObject, Client { 
    var identifier: NSUUID {
        get {
            return peripheral.identifier
        }
    }
}

protocol NetworkManager {
    var clients: [Client] { get set }
}

class CentralNetworkManager: NSObject, NetworkManager {
    var clients = [Client]()
    var peripheralClients: [PeripheralClient] {
        get {
            return clients as [PeripheralClient]
        }
    }
}

I get this runtime error when the peripheralClients Array is accessed for the first time: array element cannot be bridged to Objective-C.

From this answer to a question with a similar error, it looks like swift requires the items in an Array to be AnyObject compatible when converting to NSArray. So that means Swift's Array typecasting is using NSArray, thus making it impossible for me to downcast from an Array whose type is a protocol.

Anyone have a good suggestion for getting around this?

Community
  • 1
  • 1
Mark
  • 7,167
  • 4
  • 44
  • 68

2 Answers2

2

Did you try declaring Client as an Objective-C protocol?

@objc protocol Client {
    var identifier: NSUUID { get }
}
rob mayoff
  • 375,296
  • 67
  • 796
  • 848
0

Yeah, it seems, Swift itself does not have Array<T> to Array<U> casting functionality, it uses Obj-C facility.

Instead, to avoid that, you can cast each elements, using map for example:

var clients = [Client]()
var peripheralClients: [PeripheralClient] {
    get {
        return clients.map { $0 as PeripheralClient }
    }
}
rintaro
  • 51,423
  • 14
  • 131
  • 139