gpt4 book ai didi

swift - 我什么时候应该使用 class-only 协议(protocol)而不是 @objc?

转载 作者:可可西里 更新时间:2023-11-01 02:27:01 25 4
gpt4 key购买 nike

当我们想将协议(protocol)采用限制为类类型时,我们可以使用:class 协议(protocol)或@objc 协议(protocol)。

但是,我没有看到“仅类协议(protocol)”相对于 @objc 协议(protocol)的优势。

我知道的区别:

  1. 大小
    @objc 更节省空间。

    @objc protocol ProtocolObjC {}
    protocol ProtocolClass: class {}

    sizeof(ProtocolObjC) // -> 8
    sizeof(ProtocolClass) // -> 16
  2. 检查协议(protocol)一致性
    仅适用于@objc 协议(protocol)

    @objc protocol ProtocolObjC {}
    protocol ProtocolClass: class {}

    let obj:AnyObject = NSObject()

    obj is ProtocolObjC // -> false
    obj is ProtocolClass // < [!] error: cannot downcast from 'AnyObject' to non-@objc protocol type 'ProtocolClass'
  3. 可选协议(protocol)要求
    仅适用于@objc 协议(protocol)

    @objc protocol ProtocolObjC {
    optional func foo()
    }
    protocol ProtocolClass: class {
    optional func foo() // < [!] error: 'optional' can only be applied to members of an @objc protocol
    }

那么,有没有我们应该使用 : class 协议(protocol)的用例?或者有人知道 @objc 的缺点吗?


添加:谢谢@Antonio!

enum MyEnum { case A,B,C }

@objc protocol ProtoObjC {

// Generics
typealias FooType
var foo:FooType {get set}

// Tuple
var bar:(Int,Int) {get set}

// Enum
var baz:MyEnum {get set}
}

所有这些都会导致编译错误。

最佳答案

我认为它们是 2 个不同的东西,不能相互比较。

我的经验是,应该始终使用原生的 swift 协议(protocol),除非需要 objc 兼容性,或者除非需要仅通过 @objc 提供的特定功能..

然而,使用 swift 协议(protocol)的优点是可以使用所有 swift 相关的功能,在 objc 中不可用,例如:

  • 泛型
  • 元组
  • 快速枚举

但无论如何,我仍然会坚持使用快速协议(protocol)来进行纯粹的风格选择。

关于swift - 我什么时候应该使用 class-only 协议(protocol)而不是 @objc?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27421779/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com