14

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?

jjoelson
  • 5,771
  • 5
  • 31
  • 51

1 Answers1

45

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):

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.

rickster
  • 124,678
  • 26
  • 272
  • 326
  • 2
    Wow, great answer. The ability to constrain protocol extensions seems to me to be the biggest and most useful difference to abstract classes of the ones you mentioned. – jjoelson Jun 19 '15 at 23:22
  • I am coming back to this question probably after 3 months and feel I can understand it much better now. Can you please elaborate or add additional info to 'dynamic vs static dispatch' ? – mfaani Sep 08 '16 at 11:52
  • 2
    Static dispatch means that when you call a method that exists in more the one place, it's known at compile time which one you'll get. Dynamic dispatch means that said decision happens at run time. The NSBlog article linked above is a good place for more info on that. – rickster Sep 08 '16 at 12:32