Skip to content

Instantly share code, notes, and snippets.

@agentk
Last active January 8, 2016 14:13
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save agentk/0ea8309800b5052f7b02 to your computer and use it in GitHub Desktop.
Save agentk/0ea8309800b5052f7b02 to your computer and use it in GitHub Desktop.
public protocol HandlesStack {
func setStack(_: [Segment])
}
public protocol Router {
typealias Delegate
var handlesPath: Path -> Bool { get }
var setPath: Path -> Bool { get }
var delegate: Delegate { get }
}
public struct StackRouter<Delegate where Delegate: HandlesStack>: Router {
public let handlesPath: Path -> Bool
public let setPath: Path -> Bool
public let delegate: Delegate
public init(handlesPath: Path -> Bool, setPath: Path -> Bool, delegate: Delegate) {
self.handlesPath = handlesPath
self.setPath = setPath
self.delegate = delegate
}
}
public func createStackRouter<Delegate where Delegate: HandlesStack>(pattern: String, children: [Route] = [], delegate: Delegate) -> StackRouter<Delegate> {
let handlesPath: Path -> Bool = { path in
guard let (_, remainder) = path.splitBy(pattern) else { return false }
return children.contains { $0.handlesPath(remainder) }
}
let setPath: Path -> Bool = { path in
guard let pathRemainder = path.replace(pattern, "") else { return false }
guard let stack = buildStack(pathRemainder, children) else { return false }
delegate.setStack(stack)
return true
}
return StackRouter(handlesPath: handlesPath, setPath: setPath, delegate: delegate)
}
public protocol HandlesStack {
func setStack(_: [Segment])
}
public protocol Router {
typealias Delegate
var handlesPath: Path -> Bool { get }
var setPath: Path -> Bool { get }
var delegate: Delegate { get }
}
public struct StackRouter<Delegate where Delegate: HandlesStack>: Router {
public let handlesPath: Path -> Bool
public let setPath: Path -> Bool
public let delegate: Delegate
public init(pattern: String, children: [Route] = [], delegate: Delegate) {
handlesPath = { path in
guard let (_, remainder) = path.splitBy(pattern) else { return false }
return children.contains { $0.handlesPath(remainder) }
}
setPath = { path in
guard let pathRemainder = path.replace(pattern, "") else { return false }
guard let stack = buildStack(pathRemainder, children) else { return false }
delegate.setStack(stack)
return true
}
self.delegate = delegate
}
}
let routerFromStruct = StackRouter(pattern: pattern, children: children, delegate: delegate)
// -- vs --
let routerFromFunc = createStackRouter(pattern: pattern, children: children, delegate: delegate)
// **Further note**: the init function from the struct can be converted to same type as createStackRouter using:
let structCreateStackRouter: (String, [Route], Delegate) -> StackRouter<Delegate> = StackRouter<Delegate>.self.init
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment