Compare Value from Two Struct in Swift

How to compare two Struct objects?

In the Object Oriented World, generally, all Objects are unique to each other.

So, how I could compare two objects?

Your struct/class need to implement the Equatable Protocol which let you define how an object could be equal to another object of the same class/struct

Let's begin with this House struct:

struct House {
var street: String
}

var houseA = House.init(street: "street A, n. 10")
var houseB = House.init(street: "street A, n. 10")

houseA == houseB // of course you can't

With the Equatable protocol you can implement the static func ==. Here you can define how two object of the same class could be equal when you use the operator ==.

In my example, two objects of the struct House could be equal when they have the same street:

struct House: Equatable {
var street: String

static func == (lhs: House, rhs: House) -> Bool {
return lhs.street == rhs.street
}
}

var houseA = House.init(street: "street A, n. 10")
var houseB = House.init(street: "street A, n. 10")

houseA == houseB // now print true

Compare value from two struct in swift

To get objects of array oneData whose ID matched with ID of any object from array twoData. You can do following:

    // Array One
var oneData = [One]()
oneData = [One(ID: "1", name: "hello1", lastName: "last2"),
One(ID: "1", name: "hello2", lastName: "last2"),
One(ID: "2", name: "hello3", lastName: "last3"),
One(ID: "3", name: "hello4", lastName: "last4")]

// Array Two
var twoData = [Two]()
twoData = [Two(ID: "1", name2: "hello1", lastName2: "last1"),
Two(ID: "2", name2: "hello2", lastName2: "last2"),
Two(ID: "3", name2: "hello3", lastName2: "last3"),
Two(ID: "4", name2: "hello4", lastName2: "last4"),
Two(ID: "5", name2: "hello5", lastName2: "last5")]

let mainArray = oneData.filter { i in twoData.contains{ i.ID == $0.ID } }
print(mainArray)

Sample Image

Comparing struct values which are inside class

This gets a little cumbersome since goalDifference is optional but here is a solution with a function that compares self with another team. I assume that this is sports related and that goals always start at 0.

extension Team {
private static let emptyGoalsDifferenc = GoalsDifference(scoredGoal: .zero, passedGoal: .zero)
func best(goals: KeyPath<GoalsDifference, Int>, comparing other: Team) -> Team? {
let ownDifference = self.goalsDifference ?? Self.emptyGoalsDifferenc
let otherDifference = other.goalsDifference ?? Self.emptyGoalsDifferenc

let ownGoals = ownDifference[keyPath: goals]
let otherGoals = otherDifference[keyPath: goals]

if ownGoals == otherGoals { return nil }
return ownGoals > otherGoals ? self : other
}
}

Example

var team1 = Team(name:"Team one", goalsDifference: .init(scoredGoal: 3, passedGoal: 5))
var team2 = Team(name:"Team two", goalsDifference: .init(scoredGoal: 3, passedGoal: 2))

let bestScored = team1.best(goals: \.scoredGoal, comparing: team2)
let bestPassed = team1.best(goals: \.passedGoal, comparing: team2)

compare two values of one struct and getting extra cells in UITableView swift 4.0

First of all, you should filter out the elements from the array that you don't want to show in the table view. Then you will use that filtered array for your data source. You won't have to write the weird condition in your cellForRowAt:.. function.

class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
let arrayOne = [One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "2"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "2"), One(cellID: "1", name: "hello", lastName: "hello last", cellID2: "1")]

var filteredArray = [One]()

@IBOutlet weak var compareTableView: UITableView!

override func viewDidLoad() {
super.viewDidLoad()
// Here you apply your filter
filteredArray = arrayOne.filter { $0.cellID == $0.cellID2 }
}

func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return filteredArray.count
}

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "CompareTableViewCell") as! CompareTableViewCell
let arrayID = filteredArray[indexPath.row]
// Feed your cell
return cell
}
}

Is there way to define compare (`==`) function automatically for `struct` in Swift?

In Swift 4.1, Equatable/Hashable types now synthesize conformance to Equatable/Hashable if all of the types' members are Equatable/Hashable

SE-0185

Synthesizing Equatable and Hashable conformance

Developers have to write large amounts of boilerplate code to support equatability and hashability of complex types. This proposal offers a way for the compiler to automatically synthesize conformance to Equatable and Hashable to reduce this boilerplate, in a subset of scenarios where generating the correct implementation is known to be possible.

https://github.com/apple/swift-evolution/blob/master/proposals/0185-synthesize-equatable-hashable.md



Related Topics



Leave a reply



Submit