I need to check if a file loaded into an UIImage
object file is equal to another image and execute some actions if so. Unfortunately, it's not working.
emptyImage = UIImage(named: imageName)
if(image1.image != emptyImage) {
// do something
} else {
// do something
}
The above code always enters the if
branch.
You can implement the equality operator on UIImage
, which will ease your logic when it comes to comparing images:
func ==(lhs: UIImage, rhs: UIImage) -> Bool {
lhs === rhs || lhs.pngData() == rhs.pngData()
}
The operator compares the PNG representation, with a shortcut if the arguments point to the same UIImage
instance
This also enables the !=
operator on UIImage
.
Note that the .pngData
call and the byte-to-byte comparison might be a time consuming operation, so care to be taken when trying to compare large images.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With