Created
September 28, 2017 16:42
-
-
Save YusukeHosonuma/8798429da3d117bf3c4bc004292ecb82 to your computer and use it in GitHub Desktop.
ChainIterator.swift
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
import UIKit | |
protocol PA {} | |
protocol PB {} | |
protocol PC {} | |
protocol PD {} | |
class A : PA {} | |
class B : A, PB {} | |
class C : B, PC {} | |
class D : C, PD {} | |
let mirror = Mirror(reflecting: D()) | |
// helper function | |
func chainIterator<T>(_ value: T, _ f: @escaping (T?) -> (T?)) -> AnyIterator<T> { | |
var next: T? = value | |
return AnyIterator { | |
defer { next = f(next) } | |
return next | |
} | |
} | |
// chain superclass | |
let superclasses = chainIterator(mirror) { $0?.superclassMirror } | |
superclasses.forEach { print($0) } | |
/* | |
Mirror for D | |
Mirror for C | |
Mirror for B | |
Mirror for A | |
*/ | |
// also can use UIView | |
let v1 = UIView(); v1.tag = 1; | |
let v2 = UIView(); v2.tag = 2; v1.addSubview(v2) | |
let v3 = UIView(); v3.tag = 3; v2.addSubview(v3) | |
let v4 = UIView(); v4.tag = 4; v3.addSubview(v4) | |
let superviews = chainIterator(v4) { $0?.superview } | |
superviews.forEach { print($0.tag) } | |
/* | |
4 | |
3 | |
2 | |
1 | |
*/ |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment