gpt4 book ai didi

ios - 我可以做类似 ExpressibleByKeyPathLiteral 的东西吗?

转载 作者:行者123 更新时间:2023-11-28 05:45:01 25 4
gpt4 key购买 nike

TLDR:我可以做类似 ExpressibleByKeyPathLiteral 的东西来强制编译器为我打包我的 KeyPaths,还是这些协议(protocol)使用某种编译器魔法来使它们工作?

问题:Swift 有 ExpressibleBy*Literal 协议(protocol)族,让编译器自动装箱某些类型,如下所示:

struct Box: ExpressibleByIntegerLiteral {
typealias IntegerLiteralType = Int
let value: IntegerLiteralType
init(integerLiteral value: IntegerLiteralType) {
self.value = value
}
}

func pbox(_ box: Box...) {
for b in box {
print(b)
}
}

pbox(1,2,3)

我想知道是否有对 Swift Keypath 字面值的等效方法。例如我有:

struct PartialEquatableKeyPath<Root> {
let keyPath: PartialKeyPath<Root>
let yieldsEqualValue: (Root, Root) -> Bool
init<Value: Equatable>(_ keyPath: KeyPath<Root, Value>) {
self.keyPath = keyPath
self.yieldsEqualValue = { $0[keyPath: keyPath] == $1[keyPath: keyPath] }
}
}

extension Equatable {
func isEqual(to other: Self, byComparing keyPaths:[PartialEquatableKeyPath<Self>]) -> Bool {
return keyPaths.allSatisfy { $0.yieldsEqualValue(self, other) }
}
}

我必须这样调用:

let a = UIView()
let b = UIView()
b.isHidden = true
let keyPaths: [PartialEquatableKeyPath<UIView>] = [.init(\.isHidden), .init(\.frame)]
print(a.isEqual(to: b, byComparing: keyPaths))

我真正想要的是这样的:

extension Equatable {
func isEqual<SomeEquatable: Equatable>(_ other: Self, byComparing keyPaths:PartialEquatableKeyPath...) -> Bool {
return keyPaths.allSatisfy { $0.yieldsEqualValue(self, other) }
}
}

所以我可以这样调用它:

let a = UIView()
let b = UIView()
b.isHidden = true

print(a.isEqual(b, byComparing: \.frame.origin.x, \.isHidden))

有没有办法做到这一点? (我知道我可以让它与泛型一起工作,但前提是所有 KeyPath 都属于同一类型,而这种类型的实用性非常有限)。

最佳答案

我相信您在这里需要的是 Variadic Generics ,它在 Swift 中尚不存在,但可能有一天会存在。

作为一种解决方法,您可以制作采用一个关键路径、两个关键路径、三个关键路径等的方法版本,直到您认为合理需要使用的最高数量(然后可能是一个更多的)。您可以通过使用 Sourcery 生成变体来节省一些时间。 .

关于ios - 我可以做类似 ExpressibleByKeyPathLiteral 的东西吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55109964/

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