Created
November 22, 2016 00:11
-
-
Save annjose/043b85b26181fabe35fbbd05da024707 to your computer and use it in GitHub Desktop.
Sample code for the article on Protocol Extensions at Ray Wenderlich
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Article Name: Introducing Protocol-Oriented Programming in Swift 2 | |
// Article URL: https://www.raywenderlich.com/109156/introducing-protocol-oriented-programming-in-swift-2 | |
protocol Flyable { | |
var speed: Double { get } | |
} | |
protocol Bird { | |
var name: String { get } | |
var canFly: Bool { get } | |
} | |
extension Bird where Self: Flyable { | |
var canFly: Bool { return true } // all birds that extend Flyable can fly; so there is no need of canFly in each struct | |
} | |
struct Sparrow: Bird, Flyable { | |
var name = "Sparrow" | |
// var canFly: Bool { return true } // Sparrows can fly | |
var speed = 100.0 | |
} | |
struct Robin: Bird, Flyable { | |
var name = "Robin" | |
// var canFly: Bool { return true } // Robins can fly | |
var speed = 50.0 | |
} | |
struct Penguin: Bird { | |
var name = "Penguin" | |
var canFly: Bool { return false } // Penguins cannot fly | |
} | |
let sparrow = Sparrow() | |
sparrow.name | |
print("sparrow can fly? \(sparrow.canFly)") | |
sparrow.speed | |
let penguin = Penguin() | |
penguin.name | |
print("penguin can fly? \(penguin.canFly)") | |
// penguin.speed Penguin does not have spee because it cannot fly |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment