I have few questions for Swift developers regarding the concept of abstract classes.
I have done my homework and I know about solving these issues using methods, such as fatalError()
or preconditionFailure()
in the superclass and then overriding them in a base class. But that seems like ugly object design to me.
The reason I'm posting this is to find out whether there exists more general and universal solution.
Thanks in advance, Petr.
In object-oriented programming, an abstract type provides a base implementation that other types can inherit from in order to gain access to some kind of shared, common functionality.
Abstract methods are those types of methods that don't require implementation for its declaration. These methods don't have a body which means no implementation. A few properties of an abstract method are: An abstract method in Java is declared through the keyword “abstract”.
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.
Interface is a section of class, when you declared methods. it could be open for other classes (public, . h file) or hidden in implementation. Abstract class is a class, that is only used to create hidden subclasses and it should not have own init methods (if i understand correct).
As of today (April 7, 2016), the proposal to introduce abstract classes and methods to Swift (SE-0026) has been deferred.
Joe Groff posted the following in swift-evolution-announce on March 7, 2016:
The proposal has been deferred from Swift 3. Discussion centered around whether abstract classes fit in the direction of Swift as a "protocol-oriented" language. Beyond any religious dogmas, Swift intends to be a pragmatic language that lets users get work done. The fact of the matter today is that one of Swift's primary target platforms is the inheritance-heavy Cocoa framework, and that Swift 2's protocols fall short of abstract classes in several respects [...].
We'd like to revisit this feature once the core goals of Swift 3 have been addressed, so we can more accurately consider its value in the context of a more complete generics implementation, and so we can address the finer points of its design.
I encourage you to read the full email, but I think the conclusion is the same as what you came up with in your question: we're currently stuck with the Objective-C way of doing things (raising exceptions).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With