当关联值带有标签时,无法通过镜像获取关联值

时间:2019-03-15 00:11:31

标签: swift enums mirror associated-value

在我的代码中,我使用了协议扩展功能,该功能使用Mirror从枚举中获取关联的值。这仅适用于没有关联值标签的案例,而没有关联值标签的案例则无效。

这是协议

public protocol Enumeration { }

/// Enum extension for getting the associated value of an enum
public extension Enumeration {
    /// Get the associated value of the enum, this only works if the associated value does NOT have a label
    public var associated: (label: String, value: Any?) {
        let mirror = Mirror(reflecting: self)
        if mirror.displayStyle == .enum {
            if let associated = mirror.children.first, let key = associated.label {
                return (key, associated.value)
            }
            print("WARNING: Enumeration option of \(self) does not have an associated value")
            return ("\(self)", nil)
        }
        print("WARNING: You can only extend an enum with the Enumeration Extension")
        return ("\(self)", nil)
    }
}

现在这是我正在使用Quick btw的单元测试。     //示例枚举     私人枚举武器:枚举{         剑套(弦)         大小写匕首(速度:整数)     }

override func spec() {
    it("should have access to associated value") {
        let enchantment: String = "Fire Damage +10"
        let sword: Weapon = .sword(enchantment)
        XCTAssertEqual(sword.associated.label, "sword")
        // ===============
        // This works
        // ===============
        if let value = sword.associated.value as? String {
            XCTAssertEqual(value, enchantment)
        } else {
            XCTFail("unable to unwrap assoicated value")
        }

        let speed: Int = 12
        let dagger: Weapon = .dagger(speed: speed)
        XCTAssertEqual(dagger.associated.label, "dagger")
        // ===============
        // This does not
        // ===============
        if let value = dagger.associated.value as? Int {
            XCTAssertEqual(value, speed)
        } else {
            XCTFail("unable to unwrap associated value")
        }
    }
}

0 个答案:

没有答案