Swift中的类方法和实例方法有什么区别? [英] What's the difference between class methods and instance methods in Swift?

查看:359
本文介绍了Swift中的类方法和实例方法有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

protocol NoteProtocol {
    var body: NSString? { get set }
    var createdAt: NSDate? { get set }
    var entityId: NSString? { get set }
    var modifiedAt: NSDate? { get set }
    var title: NSString? { get set }

    // class methods
    class func insertNewNoteInManagedObjectContext(managedObjectContext: NSManagedObjectContext!) -> NoteProtocol
    class func noteFromNoteEntity(noteEntity: NSManagedObject) -> NoteProtocol

    // instance methods
    func update(#title: String, body: String)
    func deleteInManagedObjectContext(managedObjectContext: NSManagedObjectContext!)
}

嗨 这是我在GitHub上找到的一段代码.在此协议中,类方法和实例方法之间的主要区别是什么?如何定义它们? 谁能帮我吗?

Hi This is a piece of code I found on GitHub. In this protocol, what is the main difference between class methods and instance methods? How they are defined? Can anyone help me?

推荐答案

来自 实例方法

实例方法是属于特定类,结构或枚举的实例的函数.它们通过提供访问和修改实例属性的方式,或者通过提供与实例用途相关的功能,来支持这些实例的功能.

Instance methods are functions that belong to instances of a particular class, structure, or enumeration. They support the functionality of those instances, either by providing ways to access and modify instance properties, or by providing functionality related to the instance’s purpose.

即.该类的实例必须调用此方法.例子:

ie. An Instance of the class has to call this method. Example :

var a:classAdoptingNoteProtocol=classAdoptingNoteProtocol()
a.update()

类方法

如上所述,

实例方法是在特定类型的实例上调用的方法.您还可以定义在类型本身上调用的方法.这些方法称为类型方法.您可以通过在方法的func关键字之前编写关键字class来指示类的类型方法,并通过在方法的func关键字之前编写关键字static来指示结构和枚举的类型方法.

Instance methods, as described above, are methods that are called on an instance of a particular type. You can also define methods that are called on the type itself. These kinds of methods are called type methods. You indicate type methods for classes by writing the keyword class before the method’s func keyword, and type methods for structures and enumerations by writing the keyword static before the method’s func keyword.

在其他语言中它们被称为静态方法.要使用它们,这就是我要做的事情:

They are what are called as Static methods in other languages.To use them, this is what I would do:

var b=classAdoptingNoteProtocol.noteFromNoteEntity(...)

这将返回采用NoteProtocol的类的实例. IE.您不必创建类的实例即可使用它们.

This will return a instance of a class which adopts NoteProtocol. ie. you don't have to create a instance of the class to use them.

这篇关于Swift中的类方法和实例方法有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆