可比协议

时间:2019-09-19 21:27:37

标签: swift comparable swift-protocols

我正在阅读Apple的“使用Swift开发应用程序”文档,并尝试“协议”部分中的示例。在“可比较协议”部分中,我尝试了以下代码,但未在结构引用中添加Comparable,并且没有遇到任何问题,它可以正常工作:

struct Employee: Equatable {
    var firstName : String
    var lastName : String
    var jobTitle : String
    var phoneNumber : String

    static func ==(lhs: Employee, rhs : Employee) -> Bool {
        return lhs.firstName == rhs.firstName && lhs
        .lastName == rhs.lastName
    }
    static func <(lhs: Employee, rhs : Employee) -> Bool {
        return lhs.lastName < rhs.lastName
    }

}

let employee1 = Employee(firstName: "Ben", lastName: "Atkins", jobTitle: "Front Desk", phoneNumber: "415-555-7767")
let employee2 = Employee(firstName: "Vera", lastName: "Carr", jobTitle: "CEO", phoneNumber: "415-555-7768")
let employee3 = Employee(firstName: "Grant", lastName: "Phelps", jobTitle: "Senior Manager", phoneNumber: "415-555-7770")
let employee4 = Employee(firstName: "Sang", lastName: "Han", jobTitle: "Accountant", phoneNumber: "415-555-7771")
let employee5 = Employee(firstName: "Daren", lastName: "Estrada", jobTitle: "Sales Lead", phoneNumber: "415-555-7772")

let employees = [employee1, employee2, employee3, employee4, employee5]
let employeesSorted = employees.sorted(by: <)

for employee in employeesSorted {
    print(employee)
}

但是当我尝试使用大于运算符(<)进行排序时:

print("Decending")

let employeesSorted2 = employees.sorted(by: >)

for employee in employeesSorted2 {
    print(employee)
}

发生错误消息:

  

错误:在“可比较”上引用运算符“>”要求“雇员”符合“可比较”   让employeeSorted2 = employee.sorted(by:>)

您对这种不一致有有效的解释吗?

2 个答案:

答案 0 :(得分:2)

Comparable要求您实现<运算符,然后使用该函数以及==的实现来找出>,{{ 1}}和<=

仅当您声明结构为>=时,才会发生这种情况;否则,编译器将不知道要使用什么函数。

只需将您的结构声明为可比较的: Comparable

答案 1 :(得分:0)

<label class="yard/ylard" name="lya">Start Time:</label> <br> <input id="starttime" name="ly"type="time" size="20" step="1800" required> <br> <label>Finish Time:</label> <br> <input id="endtime" name="iy" type="time" size="20" step="1800" required>协议需要Comparable运算符。没有<运算符,就无法遵守Comparable<必须符合Colllection.sorted()

符合Comparable会自动为您提供Comparable>>=运算符的定义(使用您提供的<=)。如果符合<,则可以使用Comparable一致性提供的>运算符作为比较函数。

Comparable运算符不需要<协议。您可以在不遵守Comparable的情况下实现(并显式使用)<运算符。 Comparable不需要Collection.sorted(by:)一致性,您可以将Comparable运算符视为比较函数。