Skip to content

Instantly share code, notes, and snippets.

@edudnyk
Last active January 9, 2024 09:48
Show Gist options
  • Save edudnyk/74ed8d3801004a6dcaab09868b522187 to your computer and use it in GitHub Desktop.
Save edudnyk/74ed8d3801004a6dcaab09868b522187 to your computer and use it in GitHub Desktop.
SwiftUI Easter Eggs: Performance Benchmarking with _ViewTest and more
import SwiftUI
@main
struct App {
static func main() {
_TestApp().runBenchmarks([Benchmark()])
}
}
extension UIHostingController: _Test where Content == AnyView {}
extension UIHostingController: _ViewTest where Content == AnyView {
public func initRootView() -> AnyView {
return rootView
}
public func initSize() -> CGSize {
sizeThatFits(in: UIScreen.main.bounds.size)
}
}
struct ToggleView: View {
var id: String { "HackeryToggleViewID" }
var body: some View {
Toggle()._identified(by: id)
}
}
struct Toggle: View {
@State var isOn = true
var id: String { "HackeryToggleID" }
var body: some View {
SwiftUI.Toggle(isOn: $isOn, label: { Text("Hackery not allowed") })._identified(by: id)
}
}
struct PerformanceTest: _PerformanceTest {
var name = "Hackery Toggle Test"
func runTest(host: SwiftUI._BenchmarkHost, options: [Swift.AnyHashable : Any]) {
let test = _makeUIHostingController(AnyView(toggleView)) as! UIHostingController<AnyView>
test.setUpTest()
test.render()
test._forEachIdentifiedView { proxy in
let state = test.stateForIdentifier(proxy.identifier, type: Bool.self, in: type(of: test.rootView))
let view = test.viewForIdentifier(proxy.identifier, Toggle.self)
print("IDENTIFIER: \(proxy)")
print("STATE: \(state)")
print("VIEW: \(view)")
}
test.tearDownTest()
}
@ViewBuilder
var toggleView: some View {
ToggleView()
}
}
struct Benchmark: _Benchmark {
func measure(host: _BenchmarkHost) -> [Swift.Double] {
return [
host.measureAction {
PerformanceTest().runTest(host: host, options: [:])
},
// host.measureAction {
// PerformanceTest2().runTest(host: host, options: [:])
// },
// host.measureAction {
// PerformanceTest3().runTest(host: host, options: [:])
// },
]
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment