Macros are evil, but sometimes you just need them. For example, I have
struct RegionEntity { var id: Int! }
And I want to put instances of this structure in Set. Therefore, I have to comply with this Hashable protocol.
extension RegionEntity: Hashable { public var hashValue: Int { return id } } public func ==(first: RegionEntity, second: RegionEntity) -> Bool { return first.id == second.id }
Great. But what if I have dozens of such structures and the logic is the same? Maybe I can declare some protocol and disagree with Hashable. Let check:
protocol Indexable { var id: Int! { get } } extension Indexable { var hashValue: Int { return id } } func ==(first: Indexable, second: Indexable) -> Bool { return first.id == second.id }
Well, that works. And now I'm going to bind my structure to both protocols:
struct RegionEntity: Indexable, Hashable { var id: Int! }
Nope. I cannot do this because Equatable requires a == operator with Self, and for RegionEntity there is no == operator. Swift makes me copy the confirmation code for each structure and just change the name. With a macro, I could do this with only one line.
Nikolai Ischuk Feb 15 '17 at 22:13 2017-02-15 22:13
source share