Protocols in Swift - Part 4

Cracking on with protocols. Some of this will be to do with 'encapsulation' I think. Anyway, let's see what we have...!

Protocol Orientated Programming

Pasan goes over the example from the object-oriented Swift course, where we had different structures and classes.

enum Direction {
    
    case up, down, left, right
}

protocol Movable {
    
    func move (_directionL Direction, by distnace: Int)
}

protocol Destructable {
    
    func descreaseLife(by factor: Int)
}

protocol Attackable {
    
    var strength: Int { get }
    var range: Int { get }
    
    func attack(player: Player)
    

}

So all of these protocols are involved in the game I programmed before - as part of the struct/class course. The 'get' bit I'm still not too sure about. 



protocol Player: Destructable {
    
    var position: Point { get set }
    var life: Int { get set }
    
    init (x: Int, y: Int)
}

There's a lot here he does, including making one of the classes inherit from one of the new protocols. I guess that it's about using an ASPECT of behaviour, and it means there are more options and makes the code clearer. Remember the plane/bird example! You can do this with several protocols at once, so the class can now conform to various different behaviours/functions etc. Conforming to a particular type/types. 

Summary

A protocol defines a blueprint of methods, properties and other requirements for a particular task. They allow us to ENCAPSULATE common behaviour without resorting to class inheritance. The bird/plane example is the best - the one aspect is flying but you don't want all of the other inheritance!  You can inherit from multiple protocols - specify more aspects of behaviour. I get it - still not sure about some parts but it's making more sense!

Here we go...I found the options for the iPhone app course! This is a slight sideways, possible backwards step in several ways, but I really need to get hand on, direct practice with Xcode to put some of what I've learned into practice, using labels, buttons etc. linked to the code. This means that I'll come back to the 'Error Handling' course, which seems less relevant than the actual app one for now! Until then! 


Comments

Popular posts from this blog

*Xcode Project Entry 2* F1 Quiz - part 1

Angela Yu Course Part 10 (up to lesson 112)

Angela Yu Xcode 12 Course - Part 7 (lectures 74 to 79)