问题描述
我正在尝试将自定义比较中缀运算符 ==^
实现为标准相等运算符 ==
的精简版
我的应用主要面向协议,因此我试图在协议扩展中实现默认方法 static func ==^
。然而,当我让我的课程符合协议时,我收到了一个 Type 'MySourceNode' does not conform to protocol 'SourceNodeType'
错误,Xcode 要求我添加 static func ==^
协议存根。
我的问题是,如何在协议扩展中正确编写默认实现?
我试图在 SO 上找到答案,但它们中的大多数都是旧的,并且只讨论在协议扩展之外定义的通用方法。但这对我来说似乎不起作用。
这是一个带有我的协议的简化版本的游乐场文件。代码后面有一些背景信息。如果有不清楚的地方,请在评论中告诉我,我会相应地更新我的问题。
import Foundation
import SpriteKit
infix operator ==^: ComparisonPrecedence
protocol SourceNodeType: SKShapeNode {
var constrainZRotation: SKConstraint! { get set }
func setConstraints()
static func ==^ (lhs: SourceNodeType,rhs: SourceNodeType) -> Bool
}
extension SourceNodeType {
func setConstraints() {
print("Setting constraints")
}
static func ==^ (lhs: SourceNodeType,rhs: SourceNodeType) -> Bool {
lhs.frame == rhs.frame &&
lhs.position == rhs.position &&
lhs.constrainZRotation == rhs.constrainZRotation
}
}
class MySourceNode: SKShapeNode,SourceNodeType {
var constrainZRotation: SKConstraint!
}
解释这个自定义中缀运算符背后的原因。我需要它,因为我经常将 SpriteKit 的 SKShapeNodes 的子类相互比较。但我不希望类中的每个变量(如可访问性标签或名称)都进行比较,因为我在将节点添加到场景中时更改了这些值,这部分是在比较之后。
解决方法
我意识到将 func ==^
方法置于协议之外,仅使用 SourceNodeType
协议将其实现为 rhs
和 lhs
类型正是我所需要的!>
这个答案解决了我的问题:
https://stackoverflow.com/a/41390111/12764795
也许有人可以确认这是当前正确的方法?
import Foundation
import SpriteKit
infix operator ==^: ComparisonPrecedence
func ==^ (lhs: SourceNodeType,rhs: SourceNodeType) -> Bool {
lhs.frame == rhs.frame &&
lhs.position == rhs.position &&
lhs.constrainZRotation == rhs.constrainZRotation
}
protocol SourceNodeType: SKShapeNode {
var constrainZRotation: SKConstraint! { get set }
func setConstraints()
}
extension SourceNodeType {
func setConstraints() {
print("Setting constraints")
}
}
class MySourceNode: SKShapeNode,SourceNodeType {
var constrainZRotation: SKConstraint!
}
let lhsSourceNode = MySourceNode(circleOfRadius: 10)
var rhsSourceNode = MySourceNode(circleOfRadius: 10)
print(lhsSourceNode ==^ rhsSourceNode) // TRUE
rhsSourceNode.name = "Name used for testing"
print(lhsSourceNode ==^ rhsSourceNode) // TRUE
rhsSourceNode.position.y += 100
print(lhsSourceNode ==^ rhsSourceNode) // FALSE
,
问题是,你无法满足这种协议要求:
static func ==^ (lhs: SourceNodeType,rhs: SourceNodeType) -> Bool
我在 Swift Documentation 中找不到明确的解释,但是如果您尝试使类型符合该协议,它将无法编译 and it's not supposed to。
我的问题是,如何在协议扩展中正确编写默认实现?
如果您想使用 SourceNodeType
类型的参数,使用自由函数是最直接的方法,但删除运算符要求可以消除编译器错误,即:
protocol SourceNodeType: SKShapeNode {
var constrainZRotation: SKConstraint! { get set }
func setConstraints()
}
直到您尝试使用您的运营商:
let node = MySourceNode()
let otherNode = MySourceNode()
node ==^ otherNode // Generic parameter 'Self' could not be inferred
您仍然可以通过声明来解决这个问题:
extension SourceNodeType {
static func ==^ (lhs: Self,rhs: SourceNodeType) -> Bool {
lhs.frame == rhs.frame &&
lhs.position == rhs.position &&
lhs.constrainZRotation == rhs.constrainZRotation
}
}
它会按预期工作,但您仍然无法将其声明为协议要求,因为它会触发:
Protocol 'SourceNodeType' 只能用作通用约束,因为它具有 Self 或关联的类型要求
因为 rhs 是 SourceNodeType
类型。