Last active
November 10, 2015 22:10
-
-
Save cfilipov/eb3d161f964e33bd1e88 to your computer and use it in GitHub Desktop.
A Protocol-Oriented Approach for Graph Traversal in 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 Foundation | |
protocol GraphTraversable { | |
typealias GraphType : Hashable | |
var nodes: [GraphType] { get } | |
} | |
enum Status { | |
case Continue | |
case Stop | |
} | |
extension GraphTraversable where GraphType == Self { | |
func dfs(callback: GraphType -> Status) { | |
var stack = [GraphType]() | |
stack.append(self) | |
var visited = Set<GraphType>() | |
var status = Status.Continue | |
while !stack.isEmpty { | |
if status == .Stop { break } | |
let n = stack.removeLast() | |
status = callback(n) | |
visited.insert(n) | |
n.nodes.forEach { sub in | |
if visited.contains(sub) == false { | |
stack.append(sub) | |
} | |
} | |
} | |
} | |
} | |
/// | |
/// # Example Usage | |
/// | |
extension UIView : GraphTraversable { | |
var nodes: [UIView] { | |
return self.subviews | |
} | |
} | |
// UIView can now use dfs | |
window.dfs { view in | |
view.frame.origin = CGPointZero | |
return .Continue | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Note: The
Hashable
constraint can be placed onGraphType
as it is now, or onGraphTraversable
and it works the same. For example:Is the same as:
Alternately,
Hashable
can be omitted from the protocol declaration entirely and instead constrained on the protocol extension: