简体   繁体   English

Swift实例与类方法以及类继承

[英]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. 我试图使用Swift类和实例方法构建类似的东西。 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. 我创建了一个在XCode游乐场中工作的小示例。

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. 这个对象应该为我提供类似于上面的ruby代码的东西。 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"? II)是否有一种更清洁/更好的方式来实现我想要的“快速方式”?

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()

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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM