Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
807 views
in Technique[技术] by (71.8m points)

class - Compare two instances of an object in Swift

Given the following class, how can all the values in two instances be compared to each other?

// Client Object
//
class PLClient {
    var name = String()
    var id = String()
    var email = String()
    var mobile = String()
    var companyId = String()
    var companyName = String()

    convenience init (copyFrom: PLClient) {
        self.init()
        self.name =  copyFrom.name
        self.email = copyFrom.email
        self.mobile = copyFrom.mobile
        self.companyId = copyFrom.companyId
        self.companyName = copyFrom.companyName

    }

}

var clientOne = PLClient()

var clientTwo = PLClient(copyFrom: clientOne)

if clientOne == clientTwo {   // Binary operator "==" cannot be applied to two PLClient operands
    println("No changes made")
} else {
    println("Changes made. Updating server.")
}

The use-case for this is in an application which presents data from a server. Once the data is converted into an object, a copy of the object is made. The user is able to edit various fields etc.. which changes the values in one of the objects.

The main object, which may have been updated, needs to be compared to the copy of that object. If the objects are equal (the values of all properties are the same) then nothing happens. If any of the values are not equal then the application submits the changes to the server.

As is shown in the code sample, the == operator is not accepted because a value is not specified. Using === will not achieve the desired result because these will always be two separate instances.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Indicate that your class conforms to the Equatable protocol, and then implement the == operator.

Something like this:

class PLClient: Equatable 
{
    var name = String()
    var id = String()
    var email = String()
    var mobile = String()
    var companyId = String()
    var companyName = String()
    //The rest of your class code goes here

    public static func ==(lhs: PLClient, rhs: PLClient) -> Bool{
        return 
            lhs.name == rhs.name &&
            lhs.id == rhs.id &&
            lhs.email == rhs.email &&
            lhs.mobile == rhs.mobile &&
            lhs.companyId == rhs.companyId &&
            lhs.companyName == rhs.companyName
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...