Swift generics: It's all in the protocols (Part II)


Forge your own fashion

Generics aren't all about deciphering which hat goes with which dress. The great thing about Swift is that you can make your own outfits from scratch whenever you feel like it.

So let's decide a week or two ahead of the party to make our own set of rules (a protocol).
protocol PartyPerson {
    func tellUsABitAboutYourself() -> String
    var numberOfItemsOnYourPlate:Int {get}
    var isDrunk:Bool {get set}
}
 

Power to the people

And closer the time we can manufacture a couple of people along the lines of these PartyPerson etiquette rules:
class YoungSocialite:PartyPerson {
    var food:[String]
    var numberOfItemsOnYourPlate:Int {

      return food.count
    }
    var isDrunk:Bool
    
    init (units:Int, food:[String]) {
        self.food = food
        isDrunk  = units > 3 ? true : false
    }
    
    func tellUsABitAboutYourself() -> String {
        return "OMG, I go out like twice every night. OMG, I know. OMG. What a party. What a party. OMG."
    }
    
}

class ThirtySomething:PartyPerson {
    var varietiesOfCouscous:Int
    var numberOfItemsOnYourPlate:Int {
        
        return varietiesOfCouscous
    }
    var isDrunk:Bool
    
    init (units:Int, typesOfCouscous couscous:Int) {
        varietiesOfCouscous = couscous
        isDrunk  = units > 9 ? true : false
    }
    
    func tellUsABitAboutYourself() -> String {
        return "Should I have children? Or should I just keep doing this? You tell me. You look wise. Where's the toilet? What a lovely garden."
    }
    
}

let Dave = ThirtySomething(units: 8, typesOfCouscous: 5)
let Brooklyn = YoungSocialite(units: 8, food: ["Manchego & Blackberries","Sun-dried Tomato and olive oil Bruschetta","Caprese Bites"])

Party-time

Both our people (read instances) have some basic etiquette of sorts (and the barrier to entry to this party is pretty low). So now these people are inside our house (read app) and we're ready to mingle (using our generic function). It doesn't matter that they are from different classes, because they have this one thing in common: they are party people!
func mingle<P: PartyPerson>(person:P) -> String {
    return person.tellUsABitAboutYourself()
}

mingle(Dave)
mingle(Brooklyn)
What a marvellous time, such fun. Now, go home and take your drunken friend with you.

Endorse on Coderwall

Comments