In swift, why can't I instantiate a protocol when it has an initialiser? - swift

I understand that generally I cannot instantiate a protocol.
But if I include an initialiser in the protocol then surely the compiler knows that when the protocol is used by a struct or class later, it will have an init which it can use?
My code is as below and line:
protocol Solution {
var answer: String { get }
}
protocol Problem {
var pose: String { get }
}
protocol SolvableProblem: Problem {
func solve() -> Solution?
}
protocol ProblemGenerator {
func next() -> SolvableProblem
}
protocol Puzzle {
var problem: Problem { get }
var solution: Solution { get }
init(problem: Problem, solution: Solution)
}
protocol PuzzleGenerator {
func next() -> Puzzle
}
protocol FindBySolvePuzzleGenerator: PuzzleGenerator {
var problemGenerator: ProblemGenerator { get }
}
extension FindBySolvePuzzleGenerator {
func next() -> Puzzle {
while true {
let problem = problemGenerator.next()
if let solution = problem.solve() {
return Puzzle(problem: problem, solution: solution)
}
}
}
}
The line:
return Puzzle(problem: problem, solution: solution)
gives error: Protocol type 'Puzzle' cannot be instantiated

Imagine protocols are adjectives. Movable says you can move it, Red says it has color = "red"... but they don't say what it is. You need a noun. A Red, Movable Car. You can instantiate a Car, even when low on details. You cannot instantiate a Red.

But if I include an initialiser in the protocol then surely the compiler knows that when the protocol is used by a struct or class later, it will have an init which it can use?
Protocols must be adopted by classes, and there might be a dozen different classes that all adopt your Puzzle protocol. The compiler has no idea which of those classes to instantiate.
Protocols give us the power to compose interfaces without the complexity of multiple inheritance. In a multiple inheritance language like C++, you have to deal with the fact that a single class D might inherit from two other classes, B and C, and those two classes might happen to have methods or instance variables with the same name. If they both have a methodA(), and B::methodA() and C::methodA() are different, which one do you use when someone call's D's inherited methodA()? Worse, what if B and C are both derived from a common base class A? Protocols avoid a lot of that by not being directly instantiable, while still providing the interface polymorphism that makes multiple inheritance attractive.

I understand that I can't do it - I just want to understand why the
compiler can't do it?
Because protocols in Swift represent abstraction mechanism. When it comes to abstraction, you could think about it as a template, we don't have to care about the details of how it behaves or what's its properties; Thus it makes no sense to be able to create an object from it.
As a real world example, consider that I just said "Table" (as an abstracted level), I would be pretty sure that you would understand what I am talking about! nevertheless we are not mentioning details about it (such as its material or how many legs it has...); At some point if I said "create a table for me" (instantiate an object) you have the ask me about specs! and that's why the complier won't let you create object directly from a protocol. That's the point of making things to be abstracted.
Also, checking: Why can't an object of abstract class be created? might be helpful.

Unfortunately swift does not allow that even with such "hack"
You would need to use a class that confirms to that protocol as an object you refer to.

When you instantiate an object, the Operating System has to know how to allocate and deal with that kind of object in the memory: Is it a reference type (Classes)? Strong, weak or unowned reference? Or is it a value type (Structs, Strings, Int, etc)?
Reference types are stored in the Heap, while value types live in the Stack. Here is a thorough explanation of the difference between the two.
Only Reference and Value types (objects) can be instantiated. So, only the objects that conform to that protocol can then be instantiated, not the protocol itself. A protocol is not an object, it is a general description or schema of a certain behavior of objects.
As to Initialization, here what the Apple docs say:
Initialization is the process of preparing an instance of a class,
structure, or enumeration for use. This process involves setting an
initial value for each stored property on that instance and performing
any other setup or initialization that is required before the new
instance is ready for use.

Related

When and why would i use Protocols in Swift?

So I came across the subject of protocols and I have searched the internet a bunch for an answer but I couldn't find one, atleast one that solved my problem.
So I understand that Protocols are a "blueprint" of methods, properties and such and that it can be implemented in a class or struct and that it needs to conform to its requirements and such, but why would one use one?
I mean you could also just create a function inside a struct itself. It seems a bit of a hassle to write a protocol and then for the implementation of said protocol you would have to write all the requirements again with more code this time.
Is there a particular reason why one would use a protocol? Is it for safety of your code or some other reason?
For example:
In swift you have the CustomStringConvertible protocol which has a required computed property to control how custom types are represented as a printable String value, but you could also create a function inside your class which could solve this issue aswel. You could even have computed property which does the same as this protocol without even implementing this protocol.
So if someone could please shed some light onto this subject, that would be great.
Thank you in advance!
but why would one use one?
Protocols in swift are similar to Abstractions in some other languages.
before answering your question, we have to clear things out, Protocols declaration could be various but considering you have already read tons of it,
It will also be great to mention this answer here.
Now lets get into the real use case here.
Consider you have this protocol.
protocol Printable {
var name: String { get }
}
Now we need some type of structs or classes to confirm to it, or Multiple ones.
And here where it lays one of the biggest benefit of it.
Consider you have to print the name propriety of an objects.
For example those.
struct Human {
var name: String
}
struct Animal {
var name: String
}
You would simply type this without Protocols
func printOut(human: Human){
human.name
}
func printOut(animal: Animal){
animal.name
}
Which is correct, now observe the code below using protocol Printable.
struct Human: Printable {
var name: String
}
struct Animal: Printable {
var name: String
}
func printOut(object: Printable){
print(object.name)
}
It only takes us one func and so on using the Protocols.
Conclusion
Protocols used to minimize the unnecessary chunks of code.
It's name represent the effect applied on the confirm party.
Protocols can be injected as parameters types.
You can also read more about them here.
And more about the use cases here.
Protocol in swift is a pattern for allowing your classes to confirm to particular set of rules.
In other words a protocol is a blueprint of methods and properties that are necessary for a particular task.
You implement a protocol by confirming to it. If your class miss implementation of any method defined in the protocol, swift compiler tells you.
As an example lets consider that you want to make a Car class. Now there are particular requirements for a car. Like it has wheels, a trunk, etc. Each requirement can be defined as a protocol that is then implemented by the Car class. If your class don't have a trunk, you just drop the implementation.
Protocol oriented programming is a new programming paradigm. That solves some problems incurred by object oriented programming. Like multiple inheritance. Swift doesn't allow multiple inheritance but it allows confirmation to multiple protocols.
It's very easy to remove some functionality from a class in Protocol oriented programming. You just stop conforming to it. Comparative to OOP its very easy to do such things in POP.
The concept of the protocol is very simple: it's nothing more than a promise that specific methods and/or properties will exist in whatever object has taken on that protocol. And so we use them for typing and type safety.
Imagine creating a custom control, like an action sheet:
class CustomActionSheet: UIControl {
func userTappedOnSomething() {
// user tapped on something
}
}
...and you implemented it in one of your view controllers.
class SomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let actionSheet = CustomActionSheet()
}
}
This isn't much use without allowing the action sheet to communicate with the view controller when the user taps on a button. So we use a delegate:
class CustomActionSheet: UIControl {
weak var delegate: UIViewController?
func userTappedOnSomething() {
delegate?.userTookAction()
}
}
class SomeViewController: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
let actionSheet = CustomActionSheet()
actionSheet.delegate = self
}
func userTookAction() {
// update the UI
}
}
Now when the user taps on a button in the action sheet, the view controller underneath can update its UI. But this actually won't compile. You will get an error that UIViewController has no member userTookAction. That is because the UIViewController class doesn't have a method called userTookAction, only this instance of the view controller does. So we use a protocol:
protocol ActionSheetProtocol: AnyObject {
func userTookAction()
}
This protocol says that whatever object that conforms to it must include this method. So we change the action sheet's delegate to be of that protocol type and we conform the view controller to that protocol since it has such method:
class CustomActionSheet: UIControl {
weak var delegate: ActionSheetProtocol?
func userTappedOnSomething() {
delegate?.userTookAction()
}
}
class SomeViewController: UIViewController, ActionSheetProtocol {
override func viewDidLoad() {
super.viewDidLoad()
let actionSheet = CustomActionSheet()
actionSheet.delegate = self
}
func userTookAction() {
// update the UI
}
}
This is a classic example of protocol use in Swift and once you understand it, you will learn how to get crafty with protocols and use them in very clever ways. But no matter how you use them, the concept remains: promises that things will exist.
Note: In this example, I named the protocol ActionSheetProtocol, because to someone learning protocols, it makes the most sense. However, in the Swift world, in today's practice, most programmers (including the guys at Apple) would name it ActionSheetDelegate. This can be confusing for someone learning protocols so in this example I tried to make it as clear as possible. I personally don't like naming protocols delegates but there’s a lot of things I don’t like.
Note 2: I also made the protocol of type AnyObject which is Swift's syntax for making the protocol a class protocol. Not all protocols need to be of type AnyObject.

Swift - Conform third-party type to my own protocol with conflicting requirement

Here's the boiled down situation:
Let's say a third-party framework written by Alice Allman provides a very useful class:
public class AATrackpad {
public var cursorLocation: AAPoint = .zero
}
and another framework written by Bob Bell provides a different class:
public class BBMouse {
public var where_is_the_mouse: BBPoint = .zero
}
At runtime either one of these classes may be needed depending on which piece of hardware the user has decided to use. Therefore, in keeping with the Dependency Inversion Principle, I do not want my own types to depend on AATrackpad or BBMouse directly. Rather, I want to define a protocol which describes the behaviors I need:
protocol CursorInput {
var cursorLocation: CGPoint { get }
}
and then have my own types make use of that protocol instead:
class MyCursorDescriber {
var cursorInput: CursorInput?
func descriptionOfCursor () -> String {
return "Cursor Location: \(cursorInput?.cursorLocation.description ?? "nil")"
}
}
I want to be able to use an instance of BBMouse as the cursor input, like this:
let myCursorDescriber = MyCursorDescriber()
myCursorDescriber.cursorInput = BBMouse()
but in order for this to compile I have to retroactively conform BBMouse to my protocol:
extension BBMouse: CursorInput {
var cursorLocation: CGPoint {
return CGPoint(x: self.where_is_the_mouse.x, y: self.where_is_the_mouse.y)
}
}
Now that I've conformed BBMouse to my CursorInput protocol, my code compiles and my architecture is the way I want it. The reason I have no problem here is that I think that where_is_the_mouse is a terrible name for that property, and I'm quite happy to never use that name again. However, with AATrackpad its a different story. I happen to think that Alice named her cursorLocation property perfectly, and as you can see I want to be able to use the same name for my protocol requirement. My problem is that AATrackpad does not use CGPoint as the type of this property, but instead uses a proprietary point type called AAPoint. The fact that my protocol requirement (cursorLocation) has the same name as an existing property of AATrackpad but a different type means that I can't retroactively conform to CursorInput:
extension AATrackpad: CursorInput {
var cursorLocation: CGPoint { // -- Invalid redeclaration
return CGPoint(x: self.cursorLocation.x, y: self.cursorLocation.y) // -- Infinite recursion
}
}
As the comments in that snippet say, this code does not compile, and even if it did I'd be facing an infinite recursion at runtime because I have no way to specifically reference the AATrackpad version of cursorLocation. It would be great if something like this would work (self as? AATrackpad)?.cursorLocation, but I don't believe this makes sense in this context. Again though, the protocol conformance won't even compile in the first place, so disambiguating in order to solve the infinite recursion is secondary.
With all of that context in mind, my question is:
If I architect my app using protocols (which is widely recommended, for good reason), is it really true that my ability to use a certain third-party concrete type depends on the hope this third-party developer doesn't share my taste for naming conventions?
NOTE: The answer "Just pick a name that doesn't conflict with the types you want to use" won't be satisfactory. Maybe in the beginning I only had BBMouse and had no conflicts, and then a year later I decided that I wanted to add support for AATrackpad as well. I initially chose a great name and it's now used pervasively throughout my app - should I have to change it everywhere for the sake of one new concrete type? What happens later on when I want to add support for CCStylusTablet, which now conflicts with whatever new name I chose? Do I have to change the name of my protocol requirement again? I hope you see why I'm looking for a more sound answer than that.
Inspired by Jonas Maier's comment, I found what I believe to be an architecturally adequate solution to this problem. As Jonas said, function overloading exhibits the behavior that I'm looking for. I'm starting to think that maybe protocol requirements should only ever be functions, and not properties. Following this line of thinking, my protocol will now be:
protocol CursorInput {
func getCursorLocation () -> CGPoint
func setCursorLocation (_ newValue: CGPoint)
}
(Note that in this answer I'm making it settable as well, unlike in the original post.)
I can now retroactively conform AATrackpad to this protocol without conflict:
extension AATrackpad: CursorInput {
func getCursorLocation () -> CGPoint {
return CGPoint(x: self.cursorLocation.x, y: self.cursorLocation.y)
}
func setCursorLocation (_ newValue: CGPoint) {
self.cursorLocation = AAPoint(newValue)
}
}
Important - This will still compile even if AATrackpad already has a function func getCursorLocation () -> AAPoint, which has the same name but a different type. This behavior is exactly what I was wanting from my property in the original post. Thus:
The major problem with including a property in a protocol is that it can render certain concrete types literally incapable of conforming to that protocol due to namespace collisions.
After solving this in this way, I have a new problem to solve: there was a reason I wanted cursorLocation to be a property and not a function. I definitely do not want to be forced to use the getPropertyName() syntax all across my app. Thankfully, this can be solved, like this:
extension CursorInput {
var cursorLocation: CGPoint {
get { return self.getCursorLocation() }
set { self.setCursorLocation(newValue) }
}
}
This is what is so cool about protocol extensions. Anything declared in a protocol extension behaves analogously to a default argument for a function - only used if nothing else takes precedence. Because of this different mode of behavior, this property does not cause a conflict when I conform AATrackpad to CursorInput. I can now use the property semantics that I originally wanted and I don't have to worry about namespace conflicts. I'm satisfied.
"Wait a second - now that AATrackpad conforms to CursorInput, doesn't it have two versions of cursorLocation? If I were to use trackpad.cursorLocation, would it be a CGPoint or an AAPoint?
The way this works is this - if within this scope the object is known to be an AATrackpad then Alice's original property is used:
let trackpad = AATrackpad()
type(of: trackpad.cursorLocation) // This is AAPoint
However, if the type is known only to be a CursorInput then the default property that I defined gets used:
let cursorInput: CursorInput = AATrackpad()
type(of: cursorInput.cursorLocation) // This is CGPoint
This means that if I do happen to know that the type is AATrackpad then I can access either version of the property like this:
let trackpad = AATrackpad()
type(of: trackpad.cursorLocation) // This is AAPoint
type(of: (trackpad as CursorInput).cursorLocation) // This is CGPoint
and it also means that my use case is exactly solved, because I specifically wanted not to know whether my cursorInput happens to be an AATrackpad or a BBMouse - only that it is some kind of CursorInput. Therefore, wherever I am using my cursorInput: CursorInput?, its properties will be of the types which I defined in the protocol extension, not the original types defined in the class.
There is one possibility that a protocol with only functions as requirements could cause a namespace conflict - Jonas pointed this out in his comment. If one of the protocol requirements is a function with no arguments and the conforming type already has a property with that name then the type will not be able to conform to the protocol. This is why I made sure to name my functions including verbs, not just nouns (func getCursorLocation () -> CGPoint) - if any third-party type is using a verb in a property name then I probably don't want to be using it anyway :)

Abstract methods in Swift?

I have few questions for Swift developers regarding the concept of abstract classes.
How do you define an abstract class in Swift? Is there any way to prevent a class from being instantiated, while providing an initializer for its subclasses to use?
How do you define abstract methods, while implementing others? When defining abstract methods, Apple generally points you to protocols (interfaces). But they only solve the first part of my question, since all of the methods they define are abstract. What do you do when you want to have both abstract and non-abstract methods in your class?
What about generics? You might have thought about using protocols together with extensions (categories). But then there is an issue with generics because protocols can't have generic types, only typealiases.
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.
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).
There is no Abstract concept in Swift. But we can achieve that scenario by using Inheritance concept like the code below:
class ParentVC:UIViewController {
func loadInformation() {
}
}
class ChildVC:ParentVC {
// This is an Abstract Method
override func loadInformation() {
}
}
How do you define abstract methods, while implementing others?
The "swifty" way of achieving this is combining protocols and extensions, sometimes also typealiases. For data, you are going to define abstract properties in your protocol, then re-define them in a concrete class, then unite all that using a typealias and the & operator:
protocol BaseAbstract: class {
var data: String { get set }
func abstractMethod()
func concreteMethod()
}
extension BaseAbstract {
// Define your concrete methods that use the abstract part of the protocol, e.g.:
func concreteMethod() {
if !data.isEmpty {
abstractMethod()
}
}
}
class BaseImpl {
// This is required since we can't define properties in extensions.
// Therefore, we define a class with a concrete property and then
// unite it with the protocol above in the typealias below.
var data: String = "Hello, concrete!"
}
typealias Base = BaseAbstract & BaseImpl // et voila, `Base` is now ready to be subclassed
class Subclass: Base {
func abstractMethod() { // enforced by the compiler
}
}
(It can get tricker if you have generics in this scenario. Currently trying to figure it out.)

Design pattern for Swift using a protocol as a delegate

updated Clarifying question to make clear this is an issue with a protocol that has a typealias, causing the general error of can only be used as a generic constraint.
I have the following class/protocol pattern:
protocol Storage { /* ... */ }
protocol StorageView {
typealias StorageType: Storage
/* ... */
}
class StorageColumnView<StorageType:Storage>: StorageView { /* ... */ }
class SomeStorage: Storage { /* ... */ }
and I want to define a class that combines my Storage class with View class. Ideally, it would look something like:
class MyClass<S:StorageType> {
var view:ViewType<S>
}
This won't compile because you can't specify a variable's type based on a protocol. After searching around, the general answer I found was to use type-erasure and make a AnyView class. However, such an approach seems cumbersome for a single variable (in theory this is the only place I'll use it) and difficult because StorageView has enough functionality to make wrapping each variable time consuming. Additionally, the methods of the view may get called a decent amount (yes, premature optimization is the root of all evil, but its subscripts will be called in loops), so I'm worried about the overhead.
Three alternative methods I'm currently investigating are:
(1) Declaring view as AnyObject, and then casting it to the correct type:
var view:AnyObject
// ...
view = StorageColumnView(/*...*/)
// ...
if let v = view as? StorageView {
// operate on v
}
(2) Treating view as a function, and letting the type be defined using a closure:
var view: () -> StorageView
// ...
view = { return StorageColumnView(self) }
/// ...
view().doX()
(3) Parameterizing MyClass by the ViewType rather than Storage:
class MyClass<V:ViewType> {
typealias StorageType = ViewType.StorageType
}
I'm trying to evaluate which of the 3 options is best (in terms of Swift style as well as speed), or if there is another alternative I'm not aware of (or I really should just use type-erasure to solve this problem -- though it seems like AnyObject is essentially just that).
So:
Are there any major penalties for the first approach? Is this closer to c++'s static_cast or dynamic_cast?
Is there a way to make the closure approach a little more user-friendly (i.e. I rather not require the user to actually pass in a closure, but rather the type). Maybe create a helper function that is a generic that then returns the type?
While the last solution is potentially the cleanest in amount of extra code required, it also requires a design that is against what I'm trying to do. The ViewType is really supposed to act like a delegate, and be fungible. Instead, I'm not creating a specific type of MyClass based on the ViewType.
Any and all opinions welcome on the best design pattern! I'm a little surprised that making a delegate-type pattern is so difficult (assuming I'm doing things correctly), considering that is primarily how Objective-C is used in Cocoa.
Also, does anyone know the rationale for not letting a variable to be defined as a protocol type that has a typealias? What's the underlying difference between a protocol with and without a Self?

Is there a difference between Swift 2.0 protocol extensions and Java/C# abstract classes?

With the addition of protocol extensions in Swift 2.0, it seems like protocols have basically become Java/C# abstract classes. The only difference that I can see is that abstract classes limit to single inheritance, whereas a Swift type can conform to any number of protocols.
Is this a correct understanding of protocols in Swift 2.0, or are there other differences?
There are several important differences...
Protocol extensions can work with value types as well as classes.
Value types are structs and enums. For example, you could extend IntegerArithmeticType to add an isPrime property to all integer types (UInt8, Int32, etc). Or you can combine protocol extensions with struct extensions to add the same functionality to multiple existing types — say, adding vector arithmetic support to both CGPoint and CGVector.
Java and C# don't really have user-creatable/extensible "plain old data" types at a language level, so there's not really an analogue here. Swift uses value types a lot — unlike ObjC, C#, and Java, in Swift even collections are copy-on-write value types. This helps to solve a lot of problems about mutability and thread-safety, so making your own value types instead of always using classes can help you write better code. (See Building Better Apps with Value Types in Swift from WWDC15.)
Protocol extensions can be constrained.
For example, you can have an extension that adds methods to CollectionType only when the collection's underlying element type meets some criteria. Here's one that finds the maximum element of a collection — on a collection of numbers or strings, this property shows up, but on a collection of, say, UIViews (which aren't Comparable), this property doesn't exist.
extension CollectionType where Self.Generator.Element: Comparable {
var max: Self.Generator.Element {
var best = self[self.startIndex]
for elt in self {
if elt > best {
best = elt
}
}
return best
}
}
(Hat tip: this example showed up on the excellent NSBlog just today.)
There's some more good examples of constrained protocol extensions in these WWDC15 talks (and probably more, too, but I'm not caught up on videos yet):
Protocol-Oriented Programming in Swift
Swift in Practice
Abstract classes—in whatever language, including ObjC or Swift where they're a coding convention rather than a language feature—work along class inheritance lines, so all subclasses inherit the abstract class functionality whether it makes sense or not.
Protocols can choose static or dynamic dispatch.
This one's more of a head-scratcher, but can be really powerful if used well. Here's a basic example (again from NSBlog):
protocol P {
func a()
}
extension P {
func a() { print("default implementation of A") }
func b() { print("default implementation of B") }
}
struct S: P {
func a() { print("specialized implementation of A") }
func b() { print("specialized implementation of B") }
}
let p: P = S()
p.a() // -> "specialized implementation of A"
p.b() // -> "default implementation of B"
As Apple notes in Protocol-Oriented Programming in Swift, you can use this to choose which functions should be override points that can be customized by clients that adopt a protocol, and which functions should always be standard functionality provided by the protocol.
A type can gain extension functionality from multiple protocols.
As you've noted already, protocol conformance is a form of multiple inheritance. If your type conforms to multiple protocols, and those protocols have extensions, your type gains the features of all extensions whose constraints it meets.
You might be aware of other languages that offer multiple inheritance for classes, where that opens an ugly can of worms because you don't know what can happen if you inherit from multiple classes that have the same members or functions. Swift 2 is a bit better in this regard:
Conflicts between protocol extensions are always resolved in favor of the most constrained extension. So, for example, a method on collections of views always wins over the same-named method on arbitrary collections (which in turn wins over the same-named methods on arbitrary sequences, because CollectionType is a subtype of SequenceType).
Calling an API that's otherwise conflicting is a compile error, not a runtime ambiguity.
Protocols (and extensions) can't create storage.
A protocol definition can require that types adopting the protocol must implement a property:
protocol Named {
var name: String { get } // or { get set } for readwrite
}
A type adopting the protocol can choose whether to implement that as a stored property or a computed property, but either way, the adopting type must declare its implementation the property.
An extension can implement a computed property, but an extension cannot add a stored property. This is true whether it's a protocol extension or an extension of a specific type (class, struct, or enum).
By contrast, a class can add stored properties to be used by a subclass. And while there are no language features in Swift to enforce that a superclass be abstract (that is, you can't make the compiler forbid instance creation), you can always create "abstract" superclasses informally if you want to make use of this ability.