Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.