Koen Koen - 1 year ago 62
Swift Question

Can I have a Swift protocol without functions

Consider this typical example, sometimes seen in tutorials, etc (even in Apple's code):

protocol Nameable {
var name: String {get}

struct Person : Nameable {
var name: String

My question is, what would be the benefit of this pattern? I can understand it once a function is added to a protocol, but what could be a good application for a protocol with just one or more variables? Why not just add
to each

Answer Source

Persons are not the only not the only things that you may want to name. Pets have names, roads have names, heck, some people name their cars.

What if we want to name each object in a collection of different objects? If we store those objects in a collection of Any, we don't have any way to guarentee that all objects have names.

This is where protocols come in. By creating a Nameable protocol, we can create a collection of Nameable objects, and be certain that all the objects within are guaranteed to have a name.

Here's an example:

protocol Nameable {
    var name: String {get}

struct Person : Nameable {
    let name: String
    let age: Int
    // other properties of a Person

struct Pet : Nameable {
    let name: String
    let species: String
    // other properties of a Pet

struct Car : Nameable {
    let name: String
    let horsepower: Double
    // other properties of a Car

let namableItems: [Nameable] = [
    Person(name: "Steve", age: 21),
    Pet(name: "Mittens", species: "Cat"),
    Car(name: "My Pride and Joy", horsepower: 9000)

for nameableItem in namableItems {
    print("\(nameableItem.name) is a \(nameableItem.dynamicType).")

Which prints:

Steve is a Person.

Mittens is a Pet.

My Pride and Joy is a Car.

You can try it here.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download