compare - How do I implement Swift's Comparable protocol? -
how utilize comparable protocol in swift? in declaration says i'd have implement 3 operations <, <= , >=. set in class doesn't work. need have 3 of them? because should possible deduce of them single one.
the comparable protocol extends equatable protocol -> implement both of them
in apple's reference illustration apple (within comparable protocol reference) can see how should it: don't set operation implementations within class, rather on outside/global scope. have implement < operator.
correct example:
class person : comparable { allow name : string init(name : string) { self.name = name } } func < (lhs: person, rhs: person) -> bool { homecoming lhs.name < rhs.name } func == (lhs: person, rhs: person) -> bool { homecoming lhs.name == rhs.name } allow paul = person(name: "paul") allow otherpaul = person(name: "paul") allow ben = person(name: "ben") paul > otherpaul // false paul <= ben // false paul == otherpaul // true compare protocols swift
No comments:
Post a Comment