【Xcode/Swift】Eminem Explains Protocols in Swift with Pokémon: Becoming a Pokémon Trainer through Code

Yo, what’s up? It’s your boy Eminem, and today I’m gonna break down protocols in Swift for all my young fans out there. Now, imagine you’re in the world of Pokémon, and you wanna become the best Pokémon Trainer. But to be the best, you gotta understand how Pokémon battles work, right? That’s where protocols come in.

In Swift, protocols are like sets of rules or instructions that Pokémon Trainers and their Pokémon have to follow. Let’s say we have a protocol called “BattleProtocol” that defines the actions and abilities needed for a Pokémon battle. It might have rules like “attack”, “defend”, and “heal”. Now, every Pokémon that wants to participate in battles needs to follow this protocol.

Here’s how it works in code. Imagine we have two Pokémon: Pikachu and Charizard. They both wanna battle, so they need to follow the BattleProtocol. This means they have to have the same battle actions and abilities. Let’s see how we can do that:

// Define the BattleProtocol
protocol BattleProtocol {
    func attack()
    func defend()
    func heal()
}

// Create a Pikachu class that follows the BattleProtocol
class Pikachu: BattleProtocol {
    func attack() {
        print("Pikachu uses Thunderbolt!")
    }
    
    func defend() {
        print("Pikachu defends with Iron Tail!")
    }
    
    func heal() {
        print("Pikachu recovers with a Potion!")
    }
}

// Create a Charizard class that also follows the BattleProtocol
class Charizard: BattleProtocol {
    func attack() {
        print("Charizard uses Flamethrower!")
    }
    
    func defend() {
        print("Charizard defends with Wing Attack!")
    }
    
    func heal() {
        print("Charizard recovers with a Max Potion!")
    }
}

// Let the battle begin!
let pikachu = Pikachu()
let charizard = Charizard()

pikachu.attack() // Output: Pikachu uses Thunderbolt!
charizard.defend() // Output: Charizard defends with Wing Attack!
pikachu.heal() // Output: Pikachu recovers with a Potion!
charizard.attack() // Output: Charizard uses Flamethrower!

See how Pikachu and Charizard both follow the BattleProtocol? They have the same battle actions like “attack”, “defend”, and “heal”, but they can implement them differently based on their unique powers.

So, protocols in Swift help us define a set of rules or instructions that different classes or types can follow. They ensure that all the objects that follow the protocol have the same abilities and can interact with each other in a standardized way. Just like Pokémon Trainers and their Pokémon following the rules of battles.

Keep learning, keep coding, and who knows, maybe one day you’ll be the best Pokémon Trainer in the world! Until next time, stay dope, my little homies! Peace!