swift - 什么时候在 Swift 中使用 `protocol` 和 `protocol: class`?

标签 swift swift-protocols

我已经设置了一个协议(protocol)来将一些信息发送回之前的 VC。

我是这样定义的:

protocol FilterViewControllerDelegate: class  {
    func didSearch(Parameters:[String: String]?)
}

但是使用时有什么区别:

protocol FilterViewControllerDelegate  {
        func didSearch(Parameters:[String: String]?)
    }

什么时候应该使用 : class 协议(protocol)?

最佳答案

swift 4版

AnyObject 添加到这样的协议(protocol)定义中

protocol FilterViewControllerDelegate: AnyObject  {
    func didSearch(parameters:[String: String]?)
}

意味着只有一个类能够遵守该协议(protocol)。

所以鉴于此

protocol FilterViewControllerDelegate: AnyObject  {
    func didSearch(parameters:[String: String]?)
}

你可以这样写

class Foo: FilterViewControllerDelegate {
    func didSearch(parameters:[String: String]?) { }
}

不是这个

struct Foo: FilterViewControllerDelegate {
    func didSearch(parameters:[String: String]?) { }
}

swift 3版本

:class 添加到这样的协议(protocol)定义中

protocol FilterViewControllerDelegate: class  {
    func didSearch(Parameters:[String: String]?)
}

意味着只有一个类能够遵守该协议(protocol)。

所以鉴于此

protocol FilterViewControllerDelegate: class  {
    func didSearch(Parameters:[String: String]?)
}

你可以这样写

class Foo: FilterViewControllerDelegate {
    func didSearch(Parameters:[String: String]?) { }
}

不是这个

struct Foo: FilterViewControllerDelegate {
    func didSearch(Parameters:[String: String]?) { }
}

关于swift - 什么时候在 Swift 中使用 `protocol` 和 `protocol: class`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40142623/

相关文章:

swift - UIView 未正确更改颜色值 SWIFT

ios - 在 Swift 中使用 AV Audio Player 有条件地播放音频

ios - swift 核心数据 : Failed to call designated initializer on NSManagedObject

面向 Swift 协议(protocol)的混合作用域

ios - HeaderView 按钮以编程方式转到另一个 View Controller

swift - AnyObject 尝试转换为 Equatable

macos - Swift - 让 Mac App 在启动时启动

swift - fatal error : Unexpectedly found nil while

swift - 为什么 Self 和 self 有时在静态函数中指代不同的类型?

ios - 使用具有默认委托(delegate)实现的另一个协议(protocol)将委托(delegate)分配给一个类?