[swift-evolution] Operator implementation inside struct/class body
Charles Srstka
cocoadev at charlessoft.com
Mon Feb 8 17:42:57 CST 2016
> On Jan 30, 2016, at 11:03 PM, Vanderlei Martinelli via swift-evolution <swift-evolution at swift.org> wrote:
>
> Since the first public betas I’d like to know why operator implementation have to be written outside the body of its owner.
>
> Take as example the code:
>
> protocol MyEquatable {
> @warn_unused_result
> func ==(lhs: Self, rhs: Self) -> Bool
> }
>
> struct MyStruct: MyEquatable {
> let foo: String
> let bar: String
> }
>
> func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
> return lhs.foo == rhs.foo && lhs.bar == rhs.bar
> }
>
> Why we cannot write:
>
> protocol MyEquatable {
> @warn_unused_result
> func ==(lhs: Self, rhs: Self) -> Bool
> }
>
> struct MyStruct: MyEquatable {
> let foo: String
> let bar: String
>
> func ==(lhs: MyStruct, rhs: MyStruct) -> Bool {
> return lhs.foo == rhs.foo && lhs.bar == rhs.bar
> }
>
> }
>
> Any thoughts?
>
>
> -Van
+1. I’ve been meaning to write up something about this for some time. The thing I’d change is to include only the right-hand side as an argument, and use ‘self’ to refer to the left-hand side:
struct MyStruct: MyEquatable {
let foo: String
let bar: String
func ==(other: MyStruct) -> Bool {
return self.foo == other.foo && self.bar == other.bar
}
}
Charles
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160208/d457d776/attachment.html>
More information about the swift-evolution
mailing list