Skip to content

Instantly share code, notes, and snippets.

@Ridwy
Last active February 12, 2016 13:05
Show Gist options
  • Save Ridwy/b49c1ab8a96067677b99 to your computer and use it in GitHub Desktop.
Save Ridwy/b49c1ab8a96067677b99 to your computer and use it in GitHub Desktop.
Swift URL Router
class URLRouter {
let placeholders: [String: String]
init(placeholders: [String: String] = [:]) {
self.placeholders = placeholders
}
typealias ActionHandler = ((NSURL)->())
func register(path: String, handler: ActionHandler) -> Self {
let pathWithoutRoot = path.hasPrefix("/") ? path.substringFromIndex(path.startIndex.advancedBy(1)) : path
var node = root
for pattern in pathWithoutRoot.componentsSeparatedByString("/").map({ placeholders[$0] ?? $0 }) {
if pattern.isEmpty { break }
if let child = node.childlen.filter({ $0.pattern == pattern }).first {
node = child
} else {
let child = Node(pattern: pattern)
node.childlen.append(child)
node = child
}
}
if node.handler == nil {
node.handler = handler
}
return self
}
func handleURL(URL: NSURL) -> Bool {
guard let components = URL.pathComponents else { return false }
var node: Node? = nil
for component in components {
node = node == nil ? root : node?.childlen.filter({ $0.matches(component) }).first
if node == nil { break }
}
node?.handler?(URL)
return node?.handler != nil
}
private class Node {
let pattern: String
var childlen: [Node] = []
var handler: ActionHandler? = nil
init(pattern: String) {
self.pattern = pattern
}
func matches(string: String) -> Bool {
return string.rangeOfString(pattern, options:.RegularExpressionSearch) == (string.startIndex ..< string.endIndex)
}
}
private var root: Node = Node(pattern: "/")
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment