Is there a way to create an abstract class in the Swift Language, or is this a limitation just like Objective-C? I'd like to create a abstract class comparable to what Java defines as an abstract class.
Swift – Abstract classes in Swift Language
abstract classinheritancesubclassswift
Related Topic
- Objective-c – Creating an abstract class in Objective-C
- The difference between an interface and abstract class
- Python – Is it possible to make abstract classes in Python
- Java – How should I have explained the difference between an Interface and an Abstract class
- Scala: list.flatten: no implicit argument matching parameter type (Any) = > Iterable[Any] was found
- Swift – #pragma mark in Swift
- Swift Beta performance: sorting arrays
- Swift – Abstract functions in Swift Language
Best Answer
There are no abstract classes in Swift (just like Objective-C). Your best bet is going to be to use a Protocol, which is like a Java Interface.
With Swift 2.0, you can then add method implementations and calculated property implementations using protocol extensions. Your only restrictions are that you can't provide member variables or constants and there is no dynamic dispatch.
An example of this technique would be:
Notice that this is providing "abstract class" like features even for structs, but classes can also implement the same protocol.
Also notice that every class or struct that implements the Employee protocol will have to declare the annualSalary property again.
Most importantly, notice that there is no dynamic dispatch. When
logSalary
is called on the instance that is stored as aSoftwareEngineer
it calls the overridden version of the method. WhenlogSalary
is called on the instance after it has been cast to anEmployee
, it calls the original implementation (it doesn't not dynamically dispatch to the overridden version even though the instance is actually aSoftware Engineer
.For more information, check great WWDC video about that feature: Building Better Apps with Value Types in Swift