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?

2 Answers 2

2

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

@objc protocol Client {
    var identifier: NSUUID { get }
}
Sign up to request clarification or add additional context in comments.

Comments

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 }
    }
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.