Ali
Ali

Reputation: 515

Difference between type method and type instance method, etc?

Note: I've read the apple documentation and studied a swift book.

  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?

  2. Difference between class method and instance method?

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

  4. Lastly, Do class properties exist in swift?

Sorry for the confusion :'(

Upvotes: 16

Views: 9937

Answers (5)

Grzegorz R. Kulesza
Grzegorz R. Kulesza

Reputation: 1432

@PaulBart1 fix of @whyceewhite example is a little tricky, because he replace declarated PI for pi that is constant known default by swift. I rewrote this example for Swift 4 like this:

class Circle {

//static let PI = 3.14  -> error: static member 'PI' cannot be used on instance of type 'Circle'
    let PI: Double = 3.1415
    var radius: Double

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

    // Return the area of this Circle
    func area() -> Double {
        return PI * radius
    }

    // Radius class method for demonstration purposes
    static func printTypeName() {
        print("Circle")
    }

}

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

Circle.printTypeName()   // Circle
print(myCircleInstance.area()) // 14.13675
print(anotherCircleInstance.area()) // 72.56865

 //

Upvotes: 0

SLN
SLN

Reputation: 5082

It is all about scopes, it defines a boundary of where and how you can use a function. A method can only be used after you initialized an object from the class. Simply to say, in order to use the method, you have to created the object first, method belongs to the object.

But, what if you need to use a method but do not need to initiate an object, say, a global setting (ex. authorizationStatus() function in CLLocationManager for GPS coordinates authorization), you can then create a type method and simply by refer to the type name (NOT object name) and followed by the classic doc function calling.

Upvotes: 0

PaulBart1
PaulBart1

Reputation: 61

whyceewhite - thank you so much! You have clarified something that I could just not grasp! For those of you who come to this page and are operating on Swift 3+, please see the code below if you want to put the code into practice and see static in operation.

class Circle {

static let PI = 3.14

var radius: Double

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

// Returns the area of this circle
func area() -> Double {
    return Double.pi * radius
}

// Ridiculous class method for demonstration purposes
static func printTypeName() {
    print("Circle")
}
}

Then start trying Circle.printTypeName or the examples shown above! Great stuff!

Upvotes: 2

whyceewhite
whyceewhite

Reputation: 6425

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:

Upvotes: 37

Nikolay Nankov
Nikolay Nankov

Reputation: 273

The difference is that instance methods and properties are created for every instance. Type methods and properties are created for the whole type

Let's say you have struct Employee

struct Employee {
  static var ID:Int = 0
  static var NAME:Int = 1

  static func getNameOfField(index:Int) -> String {
      var fieldName:String = ""

      if index == ID {
          fieldName = "Id"
      } else if index == NAME {
          fieldName = "Name"
      }

      return fieldName
  }

  var fields = [Int:String]()

  mutating func config(id:String, name:String) {
      fields[Employee.ID] = id
      fields[Employee.NAME] = name
  }

  func getField(index:Int) -> String {
      return fields[index]!
  }
}

var e0 = Employee()
e0.config("1", name: "Mark")

var e1 = Employee()
e1.config("2", name: "John")

print(e0.getField(Employee.NAME))               // prints "Mark"
print(Employee.getNameOfField(Employee.ID))     // prints "Id"

Each instance of the struct e0 and e1 has property fields. It is created for every instance and lives in it. The values stored in the fields property are different for every instance. That's why it is called "instance property"

Each instance also has method getField. It is created for every instance and it has access to its properties and methods in that case to the instance's var fields. That's why it is called "instance method"

You access instance properties and methods by referencing the instance (in our case e0 and e1)

ID and NAME are type properties or static properties. The are created only once and have the same value for every instance and for every other object. You access type properties by referencing the "type" (in our case the struct) Employee.NAME

Type methods are something like a global function for a type(struct, class, enum). They are usually used to encapsulate functionality that is bound to the type but may not require an instance. Like in the example the type method getNameOfField(index:Int) -> String returns the field's name based on an index. To return this information you don't have to create na instance of Employee

Types are structs, classes and enums

You define type methods and properties with the keyword static (that's why they are also called static methods and properties)

Structs and enums can have type properties and type methods. Classes can only have type methods. You can create type property but it has to be computational

In classes you can define type methods with static or class keyword. The difference is that class methods can be overridden.

Upvotes: 3

Related Questions