gpt4 book ai didi

ios - 在 Swift 中使用 Comparable 扩展 @objc 协议(protocol)

转载 作者:搜寻专家 更新时间:2023-10-30 22:11:34 25 4
gpt4 key购买 nike

我正在尝试使用 Comparable 扩展我的协议(protocol) Option 以使用简单的 .sort() 方法。

下面的简短示例仅使用 Equatable 来显示错误。

@objc protocol Option: Equatable {
var title: String { get }
var enabled: Bool { get }
var position: Int { get }
}

func ==(lhs: Option, rhs: Option) -> Bool {
return lhs.position == rhs.position
}

Option 协议(protocol)必须标记为@objc 或继承自NSObjectProtocol 因为它将与UIKit 一起使用>.

错误:

  1. @objc protocol 'Option' cannot refine non-@objc protocol 'Equatable'

  2. Protocol 'Option' can only be used as a generic constraint because it has Self or associated type requirements

你对如何解决这个问题有什么建议吗?

最佳答案

Equatable仅存在于 Swift 世界中,因此您不能将其扩展为将由 Objective-C 使用的协议(protocol)。尝试这样做会导致错误 #1

具有 Self 的协议(protocol)要求(即协议(protocol)声明中的至少一个方法包含 Self )不能用作函数或变量声明的参数,只能用作通用子句的参数,例如func doSomething<T: Option>(argument: T) .

删除 Equatable来自 Option协议(protocol)声明,并声明==Option 上通用将解决编译错误。至于排序,你也可以重载 <运算符,并通过该运算符排序(无需实现 Comparable ):

@objc protocol Option {
var title: String { get }
var enabled: Bool { get }
var position: Int { get }
}

func ==<T: Option>(lhs: T, rhs: T) -> Bool {
return lhs.position == rhs.position
}

func <<T: Option>(lhs: T, rhs: T) -> Bool {
return lhs.position < rhs.position
}

这允许您将符合协议(protocol)的对象传递给 UIKit ,并在您的 swift 代码中比较它们。

class A: NSObject, Option { .. }
class B: NSObject, Option { ... }

let a = A()
let b = B()
a == b // compiles, and returns true if a and b have the same position
let c: [Option] = [a, b]
c.sort(<) // returns a sorted array by the `position` field

关于上述排序代码的一个重要说明:如果您没有为 c 指定类型, 然后编译器将其类型推断为 [NSObject] , 和 sort由于 < 的歧义,调用将无法编译运算符(operator)。您需要明确声明 c作为[Option]利用重载运算符。

关于ios - 在 Swift 中使用 Comparable 扩展 @objc 协议(protocol),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34787721/

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