如何比较两个UIDynamicProviderColor? [英] How to compare two UIDynamicProviderColor?

查看:55
本文介绍了如何比较两个UIDynamicProviderColor?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在比较使用新的iOS 13 init(dynamicProvider:)

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

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

但是当我在单元测试中将它们与 XCTAssertEqual 进行比较时,这就是运行时的结果:

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

测试代码:

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

我尝试使用扩展名覆盖 UIColor isEqual 方法,但显然没有调用它.

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

您对此有任何解决方法吗?

Do you have any workaround for this?

推荐答案

单元测试的一种解决方案是将代码更改为此:

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

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

在iOS 13运行时,它正在比较两个UIDynamicProviderColor对象,这些对象在运行块(UITraitCollection)-> UIColor"之后返回一个UIColor对象.因此,这就是您拥有两个不同对象的原因.从两者中获取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.

这篇关于如何比较两个UIDynamicProviderColor?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆