class 方法和 Swift 中的实例方法有什么区别?

What's the difference between class methods and instance methods in 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上找到的一段代码。在这个协议中,class 方法和实例方法的主要区别是什么?它们是如何定义的? 谁能帮帮我?

下面实例方法和class方法的定义(在Swift中称为类型方法)。

更多详情您可以浏览method section of the Swift documentation

实例方法:

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. Instance methods have exactly the same syntax as functions

类型方法:

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.

基本上你可以在没有实例的情况下调用类型方法(class方法):

var myNoteProtocol = NoteProtocolAdoptImplClass.noteFromNoteEntity(...);

虽然您需要实例化实例方法:

var myNoteProtocol  = NoteProtocolAdoptImplClass()
myNoteProtocol.update(...)

来自 the documentation 的部分文字:

实例方法

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.

即。 class 的实例必须调用此方法。示例:

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

Class 方法

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.

它们在其他 languages.To 中被称为静态方法,我会这样做:

var b=classAdoptingNoteProtocol.noteFromNoteEntity(...)

这将 return 一个采用 NoteProtocol 的 class 的实例。 IE。您不必创建 class 的实例即可使用它们。