swiftgenericsoverridingmutating-function

What is the more accurate difference between function overriding and function mutating? In swift particularly


Essentially both are used to modify behaviour of a function to our custom needs. But why the necessity arise to have two ways to do the same thing when both are used for same purpose.

I'm assuming, if a function has HEAD which takes parameters and a BODY which has a certain functionality with those parameters

Mutating function is used when we have to modify at the HEAD.

Mutating -> HEAD -> parameters and

Overriding function is used when we have to modify at the BODY

Overriding -> BODY -> functionality

I've searched over the internet..but found no satisfactory explanation anywhere. Please help me understand them better. Please correct me if I'm wrong.


Solution

  • Mutating

    Swift structs are immutable objects meaning that you cannot change its properties within its functions. You need to explicitly mention that you agree to make changes to its properties by adding the mutating keyword in the function definition. However this mutating jargon is required only for value types in Swift - structs and enums.

    struct MutatingExample {
        var number: Int = 0
        
    // Add 'mutating' to resolve the error
        func changeNumber(changedNumber: Int) {
            self.number = changedNumber // Error: Cannot assign to property: 'self' is immutable
        }
    }
    

    Here is an useful post that might provide you more insights - What does the Swift 'mutating' keyword mean?

    Reference types such as class do just fine and allow you to change the properties within their functions.

    Override

    Override is a concept used in inheritance. By that we can infer that override is applicable to reference types such as class and value type(struct/enums) are out of question.

    As the name implies, we use the keyword to override an existing functionality, typically that of a super class. For example,

    class Parent {
        func getName() {
            print("Parent")
        }
    }
    
    class Child: Parent {
        // Add override to resolve error
        func getName() {
            print("Child") // Error: Overriding declaration requires an 'override' keyword
        }
    }
    

    Useful link: https://www.hackingwithswift.com/sixty/8/3/overriding-methods