iosswiftaop

Does Swift support aspect oriented programming?


I am an iOS developer trying to learn aspect oriented programming but does Swift support aspect oriented programming?


Solution

  • The foundation of Aspect Oriented Programming is the intercept pattern. We start with a crosscutting requirement - something that needs to occur in many parts of the application. And then using a pointcut expression, modularize it, by identifying all of the places this requirement should be applied. This is done by intercepting a method call and weaving in additional behavior. Therefore, for a language to support AOP, it must support the intercept pattern.

    Now, depending on the language, method interception can be applied either at compile-time, run-time or both. Swift is an interesting case in this regard, as it supports the following kinds of method dispatch:

    If you extend NSObject or use the @objc decoration then messaging will be used. Otherwise Swift will revert to static/vtable method invocations.

    Summary:

    NB1: Some languages, such as Java uses a static/vtable style of method dispatch and still support runtime method interception. This is possible as they rely on virtual machine, along with a class loader, another hook-in point. In fact Java is still classed as a 'late binding' language because of this.

    NB2: Its technically possible to support provide compile time weaving against compiled-to-machine-code binaries with some limitations. The first is there aren't too many tools to support this because implementation effort is high, and must be repeated per-platform. The second is that it limits the available AOP features.