2

I am a scala developer new to swift. In scala we can share implementation across a variety of classes by "extending" a trait that has default implementations for the methods. I would like to see how to do that in swift. Here is my shot at it.

Let's consider an Alerting mechanism to be added to many application classes

protocol Alerting {
    func sendWarning(_ msg: String)
    func sendAlert(_ msg: String)
}

extension Alerting {
    func phoneHome(_ msg: String) { print(msg) }
    func sendWarning(_ msg: String) { phoneHome("WARN: \(msg)") }
    func sendAlert(_ msg: String)  { phoneHome("ALERT: \(msg)") }
}

Now let's add that Alerting to a couple of App classes:

class MyAppClass : Alerting {
    func myFunc(somethingHappened: Bool) {
        if (somethingHappened) { sendWarning("Something happened in MyAppClass.myFunc") } 
    }
}

class AnotherAppClass : Alerting {
    func anotherFunc(somethingHappened: Bool) {
        if (somethingHappened) { sendAlert("Something _bad_ happened in AnotherClass.anotherFunc") } 
    }
}

Is this a common pattern /idiom in Swift? Is there a different / more preferred approach, and why is it preferred?

Objectives for the approach:

  • Horizontally - focused functionality can be shared across disparate application classes. Think aspect oriented programming.
  • The functionality can be implemented in one place yet overridden in classes inheriting the behavior as needed
  • The behaviors are mix-ins ie they can be combined with other behaviors and do not require a rigid inheritance hierarchy

Taking a look at how my attempted implementation meets those objectives:

  • Alerting was added to two App classes that have no inherent relationship
  • The extension provides default implementations of the required behavior
  • Other unrelated protocol/extension could be added without restrictions: they meet the mix-ins goal

But I would note that my approach comes from a scala centered world and may not reflect what swift folks would prefer.

Robert Harvey
  • 200,592

0 Answers0