Created
January 31, 2025 21:34
-
-
Save stephancasas/4653f98d55a9bfcd7e0830d22e1a3515 to your computer and use it in GitHub Desktop.
An extension providing runtime value extraction and debug utilities for Swift types.
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
// | |
// Mirror+Extraction.swift | |
// | |
// Created by Stephan Casas on 1/31/25. | |
// | |
import Foundation | |
extension Mirror { | |
/// The first child of this subject whose label matches the given string. | |
func firstChild<T>(matching label: String, as type: T.Type) -> T? { | |
for child in children { | |
if child.label == label { | |
return child.value as? T | |
} | |
} | |
for child in children { | |
let childMirror = Mirror(reflecting: child.value) | |
if let found = childMirror.firstChild(matching: label, as: T.self) { | |
return found | |
} | |
} | |
return nil | |
} | |
/// The first child of the given subject whose label matches the given string. | |
static func firstChild<T>( | |
matching label: String, in subject: Any, as type: T.Type | |
) -> T? { | |
Mirror(reflecting: subject).firstChild(matching: label, as: T.self) | |
} | |
/// Crawl the given subject's internal reflection tree — printing each child's label and value. | |
static func debugPrint(_ subject: Any) { | |
Self._debugPrint(subject) | |
} | |
private static func _debugPrint(_ subject: Any, indent: String = "") { | |
let mirror = Mirror(reflecting: subject) | |
if mirror.children.isEmpty { | |
return | |
} | |
for child in mirror.children { | |
if let label = child.label { | |
print("\(indent)\(label): \(child.value)") | |
} else { | |
print("\(indent)\(child.value)") | |
} | |
Mirror._debugPrint(child.value, indent: indent + " ") | |
} | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment