Created
May 20, 2020 17:32
-
-
Save nerdsupremacist/e398a17d1e8e852020e614a5898233f5 to your computer and use it in GitHub Desktop.
Attempt at creating an AnyView from an Any
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
private protocol AnyViewConvertible { | |
func anyView() -> AnyView | |
} | |
extension View { | |
func anyView() -> AnyView { | |
return AnyView(self) | |
} | |
} | |
extension AnyViewConvertible { | |
static func anyView(value: Any) -> AnyView { | |
return (value as! Self).anyView() | |
} | |
} | |
private let witnessTable: UnsafeRawPointer = { | |
struct _SomeView: View, AnyViewConvertible { | |
var body: Never { | |
fatalError() | |
} | |
} | |
let container = unsafeBitCast(_SomeView.self as AnyViewConvertible.Type, to: ProtocolTypeContainer.self) | |
return container.witnessTable | |
}() | |
private struct ProtocolTypeContainer { | |
let type: Any.Type | |
let witnessTable: UnsafeRawPointer | |
} | |
func anyView(from view: Any) -> AnyView { | |
let viewType = type(of: view) | |
let container = ProtocolTypeContainer(type: viewType, witnessTable: witnessTable) | |
let protocolType = unsafeBitCast(container, to: AnyViewConvertible.Type.self) | |
return protocolType.anyView(value: view) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment