Reputation: 1479
I've got a conceptual Animal API client class that will interface with a Rest Api below (it may have syntax errors, I'm typing it from my head).
class AnimalApi {
let connectionInfo: ApiConnectionInfo
init(connectionInfo: ApiConnectionInfo) {
self.connectionInfo = connectionInfo
}
func login(username: String, password: String) {
// login stuff
}
func logout() {
// logout stuff
}
func get(url: String) {
}
func post(url: String) {
}
func delete(url: String) {
}
}
// Dogs
extension AnimalApi {
func getAllDogs() -> Dogs {
return get("dogResourceUrl")
}
func deleteDog() { }
func updateDog() { }
}
// Cats
extension AnimalApi {
func getAllCats() { }
func deleteCat() { }
func updateCat() { }
}
Is there a better way to group code in Swift instead of using extensions? There will be dozens of API resources I have to call that are all located on the same API server. I am trying to avoid the following...
let api = AnimalApi()
let dogs = api. // bombarded with all functions here, ideally something like api.Dogs.getAll would be more manageable
I realize that Apple uses extensions to group their code in their Swift API, but is there a better way? Sub classes maybe?
EDIT: I'd like to avoid sub classes if possible. This is because I am planning on having a single global instance of the AnimalApi since it will be accessed throughout the app constantly. Maybe make AnimalAPi members static and have separate classes with static members that contain functions that call the static AnimalApi.
class DogApi {
class func all() { return AnimalApi.get("dogResourceUri") }
}
let dogs = DogApi.all()
Upvotes: 3
Views: 1069
Reputation: 266
The below sample code is an attempt to accomplish your requirement. Hope it helps.
typealias Task = () -> ()
typealias Api = (getAll: Task, delete: Task, update: Task)
class AnimalApi {
let dogs: Api = {
func getAll() { }
func delete() { }
func update() { }
return (getAll, delete, update)
}()
let cats: Api = {
func getAll() { }
func delete() { }
func update() { }
return (getAll, delete, update)
}()
}
Now you can use it anywhere in the app as follows without getting bombarded with all different functions:
let api = AnimalApi()
let dogs = api.dogs.getAll
Upvotes: 3