如何在Swift协议扩展中为自定义中缀运算符实现默认方法
错误原因
你当前的代码存在两个核心问题导致默认实现无法被编译器识别:
- Swift不允许协议直接继承类,你写的
protocol SourceNodeType: SKShapeNode是非法写法,无法正确约束遵循协议的类型必须为SKShapeNode子类。 - 协议中声明的
==^运算符参数使用了协议类型SourceNodeType,和扩展中默认实现的签名匹配规则不符合,编译器不认为默认实现满足协议要求。
修正方案
方案1:同类型比较(推荐,符合你的业务场景)
你需要对比的是相同子类的SKShapeNode实例,修改协议声明和运算符参数为Self即可:
import Foundation import SpriteKit infix operator ==^: ComparisonPrecedence // 通过where子句约束遵循者必须是SKShapeNode子类 protocol SourceNodeType where Self: SKShapeNode { var constrainZRotation: SKConstraint! { get set } func setConstraints() // 运算符参数用Self,限定只能同类型实例比较 static func ==^ (lhs: Self, rhs: Self) -> Bool } extension SourceNodeType { func setConstraints() { print("Setting constraints") } static func ==^ (lhs: Self, rhs: Self) -> Bool { lhs.frame == rhs.frame && lhs.position == rhs.position && lhs.constrainZRotation == rhs.constrainZRotation } } class MySourceNode: SKShapeNode, SourceNodeType { var constrainZRotation: SKConstraint! }
修改后不需要在MySourceNode中添加任何额外代码,编译器会自动使用扩展中的默认实现,不会再报协议遵守错误。
方案2:跨类型比较
如果你需要支持不同SourceNodeType子类之间的比较,可以直接把运算符实现放到全局作用域,不需要在协议中声明该方法:
infix operator ==^: ComparisonPrecedence // 全局通用运算符实现,所有遵循SourceNodeType的实例都可以使用 func ==^ (lhs: SourceNodeType, rhs: SourceNodeType) -> Bool { lhs.frame == rhs.frame && lhs.position == rhs.position && lhs.constrainZRotation == rhs.constrainZRotation } protocol SourceNodeType where Self: SKShapeNode { var constrainZRotation: SKConstraint! { get set } func setConstraints() } extension SourceNodeType { func setConstraints() { print("Setting constraints") } }
内容的提问来源于stack exchange,提问作者Marco Boerner
相关产品推荐
相关产品推荐

