Skip to content

Instantly share code, notes, and snippets.

@sidepelican
Created September 17, 2019 14:04
Show Gist options
  • Save sidepelican/0155f76c25578be7341f42c50df8d82f to your computer and use it in GitHub Desktop.
Save sidepelican/0155f76c25578be7341f42c50df8d82f to your computer and use it in GitHub Desktop.
雪だるま型パラから型を順番に取り出すやつ
import Foundation
protocol _View {
static var specialType: Any.Type { get }
}
protocol View: _View {
associatedtype Body: View
associatedtype Special
var body: Body { get }
init()
}
extension View {
static var specialType: Any.Type {
return Special.self
}
}
struct Hoge<T: View>: View {
var body: some View {
T()
}
typealias Special = Int
}
struct Fuga<T: View>: View {
var body: some View {
Hoge<T>()
}
typealias Special = Float
}
struct Box<T>: View {
var body: Never {
fatalError()
}
typealias Special = T
}
struct Piyo<T: View, U: View>: View {
var body: Never {
fatalError()
}
typealias Special = (T, U)
}
extension Never: View {
var body: Never {
fatalError()
}
init() {
fatalError()
}
typealias Special = Void
}
class ExtractTypeTests: XCTestCase {
func testHoge() {
let hogefuga = Hoge<Fuga<Box<String>>>()
func extract<T: View>(_ v: T) -> [_View.Type] {
return _extract(type(of: v))
}
func _extract<T: View>(_ t: T.Type = T.self) -> [_View.Type] {
if T.self == Never.self {
return []
}
return [T.self] + _extract(T.Body.self)
}
extract(hogefuga).forEach {
print($0)
}
extract(hogefuga).forEach {
print($0.specialType)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment