问题是您的Numeric
协议不能保证+=
操作员会在场。
考虑一下:
// Numeric imposes no requirements, so this will compile
extension Range: Numeric { }
// but Range has no += operator, so +++ could not work
相反,您必须添加+=
以下要求Numeric
:
protocol Numeric: IntegerLiteralConvertible {
func +=(inout lhs: Self,rhs: Self)
}
请注意,您还需要Numeric
遵守,IntegerLiteralConvertible
以便您可以创建一个10
适当的类型来添加到它。
现在,它编译并运行良好,因为Numeric
保证它使用的所有功能都可用:
prefix operator +++{}
prefix func +++<T: Numeric>(inout operand: T) -> T {
operand += 10
return operand
}
var i = 10
+++i // i is now 20
也就是说,已经有一个协议可以满足您的需求:Strideable
所有标准数字类型都符合该协议。
protocol Strideable {
// (actually _Strideable but don’t worry about that)
/// A type that can represent the distance between two values of `Self`.
typealias Stride : SignedNumberType
// note, SignedNumberType conforms to IntegerLiteralConvertible
/// Returns a `Self` `x` such that `self.distanceTo(x)` approximates
/// `n`.
///
/// - Complexity: O(1).
///
/// - SeeAlso: `RandomAccessIndexType`'s `advancedBy`, which
/// provides a stronger semantic guarantee.
func advancedBy(n: Self.Stride) -> Self
}
并+=
使用它的实现:
func +=<T : Strideable>(inout lhs: T, rhs: T.Stride)
这意味着您可以+++
像这样实现:
prefix func +++<T: Strideable>(inout operand: T) -> T {
operand = operand.advancedBy(10)
return operand
}