Skip to content

Commit fbe164a

Browse files
committed
stdlib: Add a _bridgeAnyObjectToAny helper.
We want to be robust against unexpected `nil`s when bringing `id`s into Swift as `Any`. Add a function that builds an AnyObject?-in-an-Any when we unexpectedly receive a nil.
1 parent ade019d commit fbe164a

File tree

1 file changed

+14
-0
lines changed

1 file changed

+14
-0
lines changed

stdlib/public/core/BridgeObjectiveC.swift

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -162,6 +162,20 @@ public func _bridgeAnythingToObjectiveC<T>(_ x: T) -> AnyObject {
162162
@_silgen_name("_swift_bridgeAnythingNonVerbatimToObjectiveC")
163163
public func _bridgeAnythingNonVerbatimToObjectiveC<T>(_ x: T) -> AnyObject
164164

165+
/// Convert a purportedly-nonnull `id` value from Objective-C into an Any.
166+
///
167+
/// Since Objective-C APIs sometimes get their nullability annotations wrong,
168+
/// this includes a failsafe against nil `AnyObject`s, wrapping them up as
169+
/// a nil `AnyObject?`-inside-an-`Any`.
170+
///
171+
/// COMPILER_INTRINSIC
172+
public func _bridgeAnyObjectToAny(_ possiblyNullObject: AnyObject?) -> Any {
173+
if let nonnullObject = possiblyNullObject {
174+
return nonnullObject // AnyObject-in-Any
175+
}
176+
return possiblyNullObject // AnyObject?-in-Any
177+
}
178+
165179
/// Convert `x` from its Objective-C representation to its Swift
166180
/// representation.
167181
///

0 commit comments

Comments
 (0)