Hannes_hal
Hannes_hal

Reputation: 657

Swift instance vs class methods plus class inheritance

I have question. Coming from ruby I'm used to a syntax where I can do the following.

client = NewsAPI::Client.new(
  url:        'https://www.newshost.com/api/',
  http_token: '1234567890',
)
newsEntry = client.news.new(
  title: 'Some title',
  text: 'Some text',
);
newsEntry.save

Or

news = client.news.all

Which would give me a list of all available news.

I tried to build the something similar using Swift class and instance methods. Which worked for instance methods, but I don't know how to implement / access the class features. Like "list" or "search". I created a small example which works in a XCode playground.

So basically I have a client class, which should provide me with several "objects". In this case a news "object". This object should provide me with something similar to the ruby code above. See the code below.

To my questions: I) I could simply add these functions to my base class and override them in my subclass. This would give me the same behaviour. Even if I mix up class and instance methods. (I guess) Would this be Ok from a "best practice/design" perspective?

II) Is there a cleaner / nicer way to achieve what I want "The Swift way"?

Many thanks Johannes

class Client{
    let token: String
    public init(token: String) {
        self.token = token
    }
    public var newsObject: News {
        return News()
    }
}
class Ressource {

    class func list() {
        print("this is a news list")
    }
    class func search() {
        print("this is a news search result")
    }

    func start() {
        print("Hello")
    }
}

class News: Ressource{
    override func start() {
        print("Hello from Sub Class")
    }
}

let news = Client(token: "123456").newsObject
news.start()

Upvotes: 0

Views: 98

Answers (1)

David Pasztor
David Pasztor

Reputation: 54755

You just need to use the class type itself to access class methods. You cannot access those through an instance, since the whole point of class methods is that they not associated with an instances of the type.

You can access the list/search class methods like so:

News.list()
News.search()

Upvotes: 1

Related Questions