swiftios13

How to compare two UIDynamicProviderColor?


I'm comparing two UIColor initialised using the new iOS 13 init(dynamicProvider:)

https://developer.apple.com/documentation/uikit/uicolor/3238041-init

but that's what I get runtime when I compare them in unit test with an XCTAssertEqual:

XCTAssertEqual failed: ("Optional(<UIDynamicProviderColor: {...}; 
provider = <__NSMallocBlock__: {...}>>)") is not equal to 
("Optional(<UIDynamicProviderColor: {...}; provider = <__NSMallocBlock__: {...}>>)")

This is an example of how I create the color:

struct Style {
    static var color: UIColor {
        if #available(iOS 13.0, *) {
                return UIColor { traitCollection in
                    return traitCollection.userInterfaceStyle == .dark ? .secondarySystemBackground : UIColor.white
                }
        } else {
            return UIColor.white
        }
    }
}

The test code:

func testExample() {
    XCTAssertEqual(Style.color, Style.color)
}

I tried overriding isEqual method of UIColor with an extension but apparently it's not called.

Do you have any workaround for this?


Solution

  • One solution to your unit test is by changing your code to this:

    XCTAssertEqual(Style.color.cgColor, yourExpectedColor.cgColor)
    

    In the iOS 13 at runtime it is comparing two UIDynamicProviderColor objects that return an UIColor object after running a block "(UITraitCollection) -> UIColor". So, that's the reason you have two different objects. Getting the cgColor from both you can compare them correctly. I hope I was helpfull.