创建名称结构。一个名字有两部分一个名字(也称为给定的
姓名)和姓氏(家庭或姓氏)。名称结构应该
实施可比协议。
我试图使用以下代码,但不知道如何在比较中包括givenName、personalName、familyName和姓氏

struct Name : Comparable {
let firstName : String
let lastName: String

init(firstName : String, lastName:String) {
    self.firstName = firstName
    self.lastName=lastName
}
}func < (lhs: Name, rhs: Name) -> Bool {
return lhs.firstName < rhs.firstName && lhs.lastName < rhs.lastName
}func == (lhs: Name, rhs: Name) -> Bool {
return lhs.firstName == rhs.firstName && lhs.lastName == rhs.lastName
}

let firstName = Name(firstName: "Paul", lastName: "Smith")
let givenName = Name(firstName: "Paul" , lastName: "Smithe")
let personalName = Name(firstName: "Paul", lastName: "Smith")
print (firstName == givenName)

最佳答案

在美国,默认的排序方式是先按lastName排序,然后按firstName排序如果您所在的国家不同,您可以更改:

struct Name: Comparable {
    var firstName: String
    var lastName: String

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

    // Provide the ordering for 2 names by comparing lastName first, for example:
    //      Jane Austen < Alan Smith
    //      Alan Smith  < John Smith
    static func < (lhs: Name, rhs:Name) -> Bool {
        if lhs.lastName != rhs.lastName {
            return lhs.lastName < rhs.lastName
        } else if lhs.firstName != rhs.firstName {
            return lhs.firstName < rhs.firstName
        } else {
            return false
        }
    }
}

10-06 01:11