【问题标题】:Swift Check if Two Objects Conforming to a Protocol Are Referentially The Same快速检查两个符合协议的对象是否引用相同
【发布时间】:2016-10-04 14:52:08
【问题描述】:

我有一个构成许多类基础的协议——在下面的示例中,StaticFileRemoteFile。我有一个指向协议的变量的引用

protocol ContainerDelegate {}

protocol FileProtocol {
    var delegate: ContainerDelegate? { get set }
}

class StaticFile: NSObject, FileProtocol {
    var delegate: ContainerDelegate?
}
class RemoteFile: NSObject, FileProtocol {
    var delegate: ContainerDelegate?
}

class Container: NSObject, ContainerDelegate {
    var item: FileProtocol

    override init() {}

    func something() {
        if item.delegate !== self { // This fails
        }
    }
}

我什至不关心类型,我只想看看委托是否不是当前对象(通过引用)。使故障线正常工作的最佳方法是什么?

【问题讨论】:

标签: swift types


【解决方案1】:

您应该尝试向上转换delegate,然后检查是否相等:

func something() {
    if item.delegate as? Container !== self {
        print("hi")
    }
}

完整的工作代码示例

protocol ContainerDelegate {}
protocol FileProtocol {
    var delegate: ContainerDelegate? { get set }
}

class StaticFile: NSObject, FileProtocol {
    var delegate: ContainerDelegate?
}

class Container: NSObject, ContainerDelegate {
    var item: FileProtocol

    func something() {
        if item.delegate as? Container !== self {
            print("hi")
        }
    }

    override init() {
        item = StaticFile()
    }
}

let c = Container()
let c2 = Container()

c.item.delegate = c2
c.something() // hi gets printed

c.item.delegate = c
c.something() // hi does **not** get printed

【讨论】:

    【解决方案2】:

    这里的问题是ContainerDelegate 不要求符合类型是引用类型。您可以编写一个符合此协议的struct,而将===!== 用于结构没有意义。 (===!== 运算符采用AnyObject? 参数,并且只有类对象可以作为AnyObject 传递。)

    解决此问题的一种方法是使用protocol ContainerDelegate: class {},它需要引用语义,并且允许您编写item.delegate !== self

    另一种方式,正如 luk2302 指出的那样,由于您只关心对象是否与 self 相同,因此您可以先尝试将其转换为与 self 相同的类型,然后再进行比较。

    【讨论】:

    • 其实这个回答也帮了大忙!我只是遇到了一个无法向上转换的案例,因为我想参考比较两个 FileProtocols。
    • 使用protocol X: class 的另一个好处是它允许您使用weak var delegate: X?,这通常是您想要的委托对象。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多