gpt4 book ai didi

swift - 实现 ||= 和 &&= 运算符 : operator implementation without matching operator declaration

转载 作者:搜寻专家 更新时间:2023-10-31 08:25:47 31 4
gpt4 key购买 nike

我想要“赋值或”和“赋值和”运算符。根据Swift Standard Library Operators Reference ,这些运算符在标准库中定义。

我尝试为 Bool 值实现这些运算符:

func ||= (inout lhs: Bool, rhs: Bool) {
lhs = lhs || rhs
}

func &&= (inout lhs: Bool, rhs: Bool) {
lhs = lhs && rhs
}

但编译器会提示:没有匹配运算符声明的运算符实现

这可以通过定义运算符来解决:

infix operator ||= { associativity right precedence 90 }

infix operator &&= { associativity right precedence 90 }

但我不确定这样做是否正确。为什么标准库中的定义不起作用?另外,我注意到根据 operator reference 标准库没有针对任何类型的这些运算符的实现。这是为什么?这是疏忽还是有意为之?

最佳答案

有关运算符的文档已过时,之前已在 this answer 的评论中指出;我引用用户 Airspeed Velocity:

Yup, checked and it (ed. note: referring to operator &&=) was only ever defined as an operator in very in early versions, and never actually implemented in any function, then removed altogether later. Docs are wrong.

您可以通过 Cmd - 在 Swift 中单击

轻松查看哪些运算符实际上是 native 定义的
import Swift

例如 Playground 。

或者,查看 Policy.swift 源代码中的标准运算符部分:

在上面的两个例子中,很明显 &&=||= 都不是本地定义的。


如果您对这些运算符的实现方式感兴趣(回到 Swift 1.1),可能会对以下帖子感兴趣:

关于swift - 实现 ||= 和 &&= 运算符 : operator implementation without matching operator declaration,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35768889/

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