What's the Difference Between Class Methods and Instance Methods in Swift

What's the difference between class methods and instance methods in Swift?

Some text from the documentation:

Instance Methods

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

Class Methods

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

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.... Class method vs. Instance method

If you're asking a question you should reduce your code to a minimum, discarding unnecessary details.

You probably want something like this:

class MyClass {
let x = MyClass.getStuff()

static func getStuff() -> Int {
return 0
}
}

However your method getWallImages() can't do something like this, because it's returning the result asynchronous, which means you get the result much later after the function has returned.

You could do something like this though (this is how I'd be doing it):

class MyClass {
var x : Int? {
didSet {
if let x = x {
// Do something with x, here it's assigned
} else {
// x was set to nil, something failed
}
}
}

init() {
getStuffAsynchronous()
}

func getStuffAsynchronous() {
// Do your query stuff here, assign x to your objects to invoke the didSet
x = 0

// If it fails somehow, assign set x to nil
// if fail {
// x = nil
// }
}
}

The difference between Swift's instance methods and type methods

A class method is useful when you want to connect some kind of functionality to a class without forcing the client to instantiate that class, and when a method doesn't depend on the state of a particular object.

In an object-oriented approach to programming they are often used in place of traditional utility-style functions, which take some sort of input and return output without referencing a particular object, e.g., an HTTP routing system with class methods "Post" and "Get" that takes a url and query parameters as arguments and sends a request to the server. These functions are useful across a range of different classes and don't necessarily need to be represented by an underlying instance variable.

They can also be used to include comparison functions where both objects are of the same class. Say you're trying to calculate the dot product of two matrix objects--it doesn't make sense to prefer one object as the basis on which to compare the other and not the other way around--especially since calculation of a dot product has no consequences for either underlying matrix object. The preferred solution then is something like:

 class func dotProduct(a: Matrix, b: Matrix) -> Double

What is the difference between class and instance methods?

Like most of the other answers have said, instance methods use an instance of a class, whereas a class method can be used with just the class name. In Objective-C they are defined thusly:

@interface MyClass : NSObject

+ (void)aClassMethod;
- (void)anInstanceMethod;

@end

They could then be used like so:

[MyClass aClassMethod];

MyClass *object = [[MyClass alloc] init];
[object anInstanceMethod];

Some real world examples of class methods are the convenience methods on many Foundation classes like NSString's +stringWithFormat: or NSArray's +arrayWithArray:. An instance method would be NSArray's -count method.

instance methods from class methods swift

What you are trying to do rarely makes any sense from a design perspective.

By definition, an instance method operates on an instance of an object.
For example, it might require access to some instance members, or somehow meddle with the state of the object you call the method on.

class methods on the other hand do not require an instance to be able to call them - and should in general only operate on the given parameters, not be dependant on shared state.

If you need to call instanceMethod() in classMethod(), and instanceMethod() does not require any state - why is it not also a class method, or a (global) pure function?

Difference between type method and type instance method, etc?

In Swift, types are either named types or compound types. Named types include classes, structures, enumerations, and protocols. In addition to user-defined named types, Swift defines many named types such as arrays, dictionaries, and optional values. (Let's ignore compound types for now since it doesn't directly pertain to your question.)

To answer your questions, suppose that I create a user defined class called Circle (this is just an example):

class Circle {

static let PI = 3.14

var radius: Double

init(radius: Double) {
self.radius = radius
}

// Returns the area of this circle
func area() {
return PI * radius
}

// Ridiculous class method for demonstration purposes
static func printTypeName() {
println("Circle")
}
}
  1. I'm confused on the difference between a "type instance method"
    (if such exists, correct me if I'm wrong) and a type method?

As mentioned earlier, a type refers to a class, structure, enumeration, protocol, and compound types. In my example above, I use a class called Circle to define a type.

If I want to construct an individual object of the Circle class then I would be creating an instance. For example:

let myCircleInstance = Circle(radius: 4.5)
let anotherCircleInstance = Circle(radius: 23.1)

The above are objects or instances of Circle. Now I can call instance methods on them directly. The instance method defined in my class is area.

let areaOfMyCircleInstance = myCircleInstance.area()

Now, a type method is a method that can be called directly on the type without creating an instance of that type.

For example:

Circle.printTypeName()

Notice that there is a static qualifier before the func. This indicates that it pertains to the type directly and not to an instance of the type.


  1. Difference between class method and instance method?

See the explanation above.


  1. Difference between type property and instance property(if such
    exists, sorry I'm very confused on Type Properties subject)?

This is a similar explanation to the one in your question one except that instead of applying to methods, it applies to the properties (i.e., attributes, variables) of the type.

In my Circle example, the properties are defined as:

static let PI = 3.14
var radius: Double

The property PI is a type property; it may be accessed directly by the type

Circle.PI

The property radius is an instance property of the type; it may be accessed by an instance of the type. Using the variables we created earlier:

// I can do this; it will be 4.5
myCircleInstance.radius

// And this; it will be 23.1
anotherCircleInstance.radius

// But I CANNOT do this because radius is an instance property!
Circle.radius

  1. Lastly, Do class properties exist in swift?

Absolutely! Read my explanation to your question 3 above. The PI property in my example is an example of a class property.

References:

  • Swift Language Reference - Types
  • Swift Language Reference - Properties
  • Swift Language Reference - Methods

is there any advantage when use class method instead of instance method?

My explanation is a little different.

Instance methods are sent to an INSTANCE of a class. An instance of a class is a concrete thing. It has state data that persists for the life of the object. When you send a message to an object, it can use that state data to do things, and it can remember information for later.

Class methods are sent to the class as a whole. A class is a more abstract concept. Classes do not save state data, at least in Objective C (In other languages like C++, there are class variables that belong to the entire class, but Objective C does not have class variables.)

Lets move to an example of a car factory

The car factory is the class. The car class has a class method buildCar. The buildCar method takes parameters that tell what color the car should be, how big the engine should be, what options it should have, etc. You sent the car factory (the class) a buildCar message, and it creates and returns an instance of that class (the car factory builds you a car and gives it to you.)

Once you've created a car, that particular car has state variables that store things like the channel on the radio, the amount of gas left in the tank, the milage ("kilometerage"?) on the odometer, the wear level on the brakes, etc. Different cars will have different values for those variables.

You can ask an individual car how much gas is left in it's tank. (instance method.) Car A might have a full tank, and car B might be nearly empty.

However, it would not make sense to ask the car factory how much gas it has in the tank. A car factory doesn't have a gas tank. However, you could ask a car factory about the types of cars that it can build and the options for those cars. That is static information that always holds true for that car factory.

In addition to "factory methods" (e.g. build me a car), you can use class methods like you use functions in a procedural language. A class method is self-contained. You pass all the parameters into the method that you need in order to do whatever task is required, and you get back a single result (or no result for a void class method.) Once the class method is done executing, there is no state data left to record what happened.

Purpose of Instance Methods vs. Class Methods in Objective-C

Generally speaking, you should create instance methods when you need code that operates on a specific instance of an object. You create a class method when you need to do something that involves that class in general but probably doesn't operate on any specific objects of that class.

In practice, you will find that nearly all of your methods should be instance methods. Just take a look at any existing Objective-C class like NSString, NSArray, UIView, etc. and you'll see that the vast majority of their methods are instance methods. The most common use of class methods (again, look at the classes I mentioned) are for convenience constructors that return autorelease objects, or singleton accessors.

Consider the length method in NSString. Why is this an instance method and not a class method? It is an instance method because it only makes sense to ask a specific instance of NSString what its length is. Asking NSString in general for a length (i.e. if length was a class method) wouldn't make any sense.

On the other hand, let's say that we want to add a method to NSNumber that will return the maximum integer value that can be stored on a given system. In this case, it should be a class method because we're just asking a general question of NSNumber that is independent of any specific instance.

What are the differences between functions and methods in Swift?

After a few hours of reading and experimenting, here are the things that I found out:-

Functions in Swift

Functions are self-contained chunks of code that perform a specific
task. You give a function a name that identifies what it does, and
this name is used to “call” the function to perform its task when
needed.

Resource: Official Apple Documentation on Functions in Swift

Function Parameter Names

However, these parameter names are only used within the body of the
function itself, and cannot be used when calling the function. These
kinds of parameter names are known as local parameter names, because
they are only available for use within the function’s body.

It means that by default, all the parameters for Function are local parameters.

But, sometimes we want to indicate the purpose of each parameter. So, we can actually define an external parameter name for each parameter. Example Code:

func someFunction(externalParameterName localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}

Another way to make the external parameter name is using hash symbol (#) to shorten the name.

func someFunction(#localParameterName: Int) {
// function body goes here, and can use localParameterName
// to refer to the argument value for that parameter
}

To call the above functions with external parameter, you may use

someFunction(localParameterName:10)

Methods in Swift

Methods are functions that are associated with a particular type.
Classes, structures, and enumerations can all define instance methods,
which encapsulate specific tasks and functionality for working with an
instance of a given type.

Resource: Official Apple Documentation on Methods in Swift

However, the default behavior of local names and external names is
different for functions and methods.

Specifically, Swift gives the first parameter name in a method a local
parameter name by default
, and gives the second and subsequent
parameter names both local and external parameter names by default.

Code below shows the differences for default and non-default parameters for method in Swift.

import Foundation
import UIKit

class ViewController2: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()

//Default methods calling
var dailyStatement = greet("Rick", day: "Tuesday")
println(dailyStatement)

//First parameter is also an external parameter
var dailyStatement2 = greet2(name:"John", day: "Sunday")
println(dailyStatement2)
}

//Default: First Parameter is the local parameter, the rest are external parameters
func greet (name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}

//Use Hash symbol to make the First parameter as external parameter
func greet2 (#name: String, day: String) -> String {
return "Hello \(name), today is \(day)."
}
}

I might miss some important details. Hope someone can provide a better answer.



Related Topics



Leave a reply



Submit