Skip to content

Instantly share code, notes, and snippets.

@chriseidhof
Created August 17, 2014 21:04
Show Gist options
  • Star 49 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save chriseidhof/1fc977ffb856dbcdc113 to your computer and use it in GitHub Desktop.
Save chriseidhof/1fc977ffb856dbcdc113 to your computer and use it in GitHub Desktop.
Type-safe routes in Swift
//
// 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