Home > Mobile >  Swift - How can I force every method in a class to call specific function?
Swift - How can I force every method in a class to call specific function?

Time:05-12

In other words, I'd like to find a way to avoid typing code used repeatedly in every class method like the following example.

Codes:

class SampleClass {
    func common() {
        print("It's done")
    }
    
    func first() {
        print("First fucntion is excuted")
        self.common()
    }
    
    func second() {
        print("First fucntion is excuted")
        self.common()
    }
    
    func third() {
        print("First fucntion is excuted")
        self.common()
    }
}

Result:

SampleClass().first() 
// First fucntion is excuted
// It's done

SampleClass().second() 
// Second fucntion is excuted
// It's done

SampleClass().third() 
// Third fucntion is excuted
// It's done

As you can see method common() is executed in every class methods.

What I want to do here is rather than writing common() method in every method, making all methods run it automatically.

Are there any functions or patterns to do this in Swift? If so, please let me know.

Thanks!

CodePudding user response:

A possible way is to call common and pass a closure

class SampleClass {
    func common(action: @escaping () -> Void) {
        action()
        print("It's done")
    }
    
    func first() { print("First function is executed") }
    func second() { print("Second function is executed") }
    func third() { print("Third function is executed") }
}

let sample = SampleClass()
sample.common(action: sample.first)
// First function is executed
// It's done

sample.common(action: sample.second)
// Second function is executed
// It's done

sample.common(action: sample.third)
// Third function is executed
// It's done
  • Related