Hadeel Hadeel - 2 months ago 48
Swift Question

Swift 3 comparable protocol

Create a Name structure. A name has two parts a first name (also called a given
name or personal name) and a last name (family or surname). The Name structure should
implement the Comparable protocol.

I was trying with the following code but I don't know how to include the givenName, personalName,familyName and surName in the comparison

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)

Answer

In America the default is to sort by lastName first, firstName second. You may change this if it's different in your country:

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
        }
    }
}