Created
August 17, 2014 21:04
-
-
Save chriseidhof/1fc977ffb856dbcdc113 to your computer and use it in GitHub Desktop.
Type-safe routes in Swift
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
// | |
// main.swift | |
// Routes | |
// | |
// Created by Chris Eidhof on 17/08/14. | |
// Copyright (c) 2014 Chris Eidhof. All rights reserved. | |
// | |
import Foundation | |
enum Github { | |
case Zen | |
case UserProfile(String) | |
} | |
protocol Path { | |
var path : String { get } | |
} | |
extension Github : Path { | |
var path: String { | |
switch self { | |
case .Zen: return "/zen" | |
case .UserProfile(let name): return "/users/\(name)" | |
} | |
} | |
} | |
let sample = Github.UserProfile("ashfurrow") | |
println(sample.path) // Prints "/users/ashfurrow" | |
// So far, so good | |
protocol Moya : Path { | |
var baseURL: NSURL { get } | |
var sampleData: String { get } // Probably JSON would be better than AnyObject | |
} | |
extension Github : Moya { | |
var baseURL: NSURL { return NSURL(string: "https://api.github.com") } | |
var sampleData: String { | |
switch self { | |
case .Zen: return "Half measures are as bad as nothing at all." | |
case .UserProfile(let name): return "{login: \"\(name)\", id: 100}" | |
} | |
} | |
} | |
func url(route: Moya) -> NSURL { | |
return route.baseURL.URLByAppendingPathComponent(route.path) | |
} | |
println(url(sample)) // prints https://api.github.com/users/ashfurrow |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment