简体   繁体   English

使用协议时,Swift Array向下转换运行时错误

[英]Swift Array downcasting runtime error when using a protocol

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 . 第一次访问peripheralClients数组时出现此运行时错误: 数组元素无法桥接到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 . 从这个答案到一个类似错误的问题,看来swift要求将Array中的项目转换为NSArray时必须与AnyObject兼容。 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. 因此,这意味着Swift的Array类型转换使用的是NSArray,从而使我无法从类型为协议的Array向下转换。

Anyone have a good suggestion for getting around this? 有人对此有很好的建议吗?

Did you try declaring Client as an Objective-C protocol? 您是否尝试将Client声明为Objective-C协议?

@objc protocol Client {
    var identifier: NSUUID { get }
}

Yeah, it seems, Swift itself does not have Array<T> to Array<U> casting functionality, it uses Obj-C facility. 是的,似乎,Swift本身没有Array<T>Array<U>转换功能,它使用Obj-C工具。

Instead, to avoid that, you can cast each elements, using map for example: 为了避免这种情况,您可以使用map强制转换每个元素,例如:

var clients = [Client]()
var peripheralClients: [PeripheralClient] {
    get {
        return clients.map { $0 as PeripheralClient }
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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