Skip to content

Commit 5164280

Browse files
authored
(151258374) Retrieving attributed string attribute values should not use identity casts (#1290)
1 parent 88f6454 commit 5164280

File tree

1 file changed

+8
-6
lines changed

1 file changed

+8
-6
lines changed

Sources/FoundationEssentials/AttributedString/AttributedStringAttributeStorage.swift

Lines changed: 8 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -54,18 +54,20 @@ extension AttributedString {
5454
func rawValue<K: AttributedStringKey>(
5555
as key: K.Type
5656
) -> K.Value where K.Value: Sendable {
57-
func extractValue<RealValue>(_ value: RealValue) -> K.Value {
58-
assert(RealValue.self == K.Value.self, "_AttributeValue raw value can only be retrieved with a key whose value matches the stored attribute value (stored type \(RealValue.self) does not match key value type \(K.Value.self))")
59-
return _identityCast(value, to: K.Value.self)
57+
// Dynamic cast instead of an identity cast to support bridging between attribute value types like NSColor/UIColor
58+
guard let value = self._rawValue as? K.Value else {
59+
preconditionFailure("Unable to read \(K.self) attribute: stored value of type \(type(of: self._rawValue)) is not key's value type (\(K.Value.self))")
6060
}
61-
return _openExistential(self._rawValue, do: extractValue)
61+
return value
6262
}
6363

6464
static func ==(left: Self, right: Self) -> Bool {
6565
func openEquatableLHS<LeftValue: Hashable & Sendable>(_ leftValue: LeftValue) -> Bool {
6666
func openEquatableRHS<RightValue: Hashable & Sendable>(_ rightValue: RightValue) -> Bool {
67-
assert(LeftValue.self == RightValue.self, "Two _AttributeValues can only be compared if they are of the same attribute value type")
68-
let rightValueAsLeft = _identityCast(rightValue, to: LeftValue.self)
67+
// Dynamic cast instead of an identity cast to support bridging between attribute value types like NSColor/UIColor
68+
guard let rightValueAsLeft = rightValue as? LeftValue else {
69+
return false
70+
}
6971
return rightValueAsLeft == leftValue
7072
}
7173
return openEquatableRHS(right._rawValue)

0 commit comments

Comments
 (0)