Skip to content

Instantly share code, notes, and snippets.

@nerdsupremacist
Created May 20, 2020 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save nerdsupremacist/e398a17d1e8e852020e614a5898233f5 to your computer and use it in GitHub Desktop.
Save nerdsupremacist/e398a17d1e8e852020e614a5898233f5 to your computer and use it in GitHub Desktop.
Attempt at creating an AnyView from an Any
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