Created
March 4, 2016 01:43
-
-
Save tarunon/61e188cda2802cee9a45 to your computer and use it in GitHub Desktop.
App URL Schemeをマッチングしてみる
This file contains hidden or 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 | |
| enum URLMatchResult<T> { | |
| case Match(T) | |
| case Mismatch | |
| } | |
| protocol URLHandlerBaseType { | |
| func handle(url: NSURL) | |
| } | |
| protocol URLHandlerType: URLHandlerBaseType { | |
| typealias MatchValueType | |
| func match(url: NSURL) -> URLMatchResult<MatchValueType> | |
| func handle(value: MatchValueType) | |
| } | |
| extension URLHandlerType { | |
| func handle(url: NSURL) { | |
| switch match(url) { | |
| case .Match(let value): | |
| handle(value) | |
| case .Mismatch: | |
| break | |
| } | |
| } | |
| } | |
| struct AnyURLHandler<T>: URLHandlerType { | |
| typealias Matcher = NSURL -> URLMatchResult<T> | |
| typealias Handler = T -> () | |
| let matcher: Matcher | |
| let handler: Handler | |
| init(matcher: Matcher, handler: Handler) { | |
| self.matcher = matcher | |
| self.handler = handler | |
| } | |
| init<H: URLHandlerType where H.MatchValueType == T>(handler: H) { | |
| self.matcher = handler.match | |
| self.handler = handler.handle | |
| } | |
| func match(url: NSURL) -> URLMatchResult<T> { | |
| return matcher(url) | |
| } | |
| func handle(value: T) { | |
| handler(value) | |
| } | |
| } | |
| class URLRouter { | |
| static let sharedRouter = URLRouter() | |
| var handlers = [URLHandlerBaseType]() | |
| private init () { | |
| } | |
| func addURLHandler<H: URLHandlerType>(handler: H) { | |
| handlers.append(handler) | |
| } | |
| func addURLHandler<T>(matcher: NSURL -> URLMatchResult<T>, handler: T -> ()) { | |
| handlers.append(AnyURLHandler(matcher: matcher, handler: handler)) | |
| } | |
| func openURL(url: NSURL) { | |
| handlers.forEach { $0.handle(url) } | |
| } | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment