Skip to content

Instantly share code, notes, and snippets.

@jamesrochabrun
Created December 9, 2016 05:24
Show Gist options
  • Save jamesrochabrun/05991c3e59fd14bdec6368b5d523f6ca to your computer and use it in GitHub Desktop.
Save jamesrochabrun/05991c3e59fd14bdec6368b5d523f6ca to your computer and use it in GitHub Desktop.
//DEFINING A PROTOCOL
import Foundation
protocol FullNameable {
var fullName: String { get }
}
struct User: FullNameable {
var fullName: String
}
let user = User(fullName: "carlos casas")
struct Friend: FullNameable {
let firstName: String
let lastName: String
//computer property
var fullName: String {
return "\(firstName) \(lastName) "
}
}
let friend = Friend(firstName: "carlos", lastName: "casas")
friend.fullName
//MODELING BEHAVIOUR WITH PROTOCOLS
enum EmployeeType {
case manager
case traditional
}
struct Paycheck {
let base: Double
let benefits: Double
let deductions: Double
let vacation: Double
}
protocol Payable {
func pay() -> Paycheck
}
class Employee {
let name: String
let address: String
let startDate: Date
let type: EmployeeType
init(name:String, address:String, startDate: Date, type:EmployeeType) {
self.name = name
self.address = address
self.startDate = startDate
self.type = type
}
}
class HourlyEmployee: Employee, Payable {
var hourlyWage = 15.00
var hoursWorked = 0.0
let vacation = 0
func pay() -> Paycheck {
let base = hoursWorked * hourlyWage
return Paycheck(base: base, benefits: 0, deductions: 0, vacation: 0)
}
}
class SalariedEmployee: Employee, Payable {
var salary = 5000.00
var benefits = 1000.00
var deductions = 0.0
var vacation = 0.0
func pay() -> Paycheck {
let monthly = salary/12
return Paycheck(base: monthly, benefits: benefits, deductions: deductions, vacation: vacation)
}
}
//Using a protocol as a parameter type in an external function
func pay(employee: Payable) {
employee.pay()
}
let employee = SalariedEmployee(name: "j", address: "add", startDate: Date(), type: .traditional)
pay(employee: employee)
//PROTOCOL AS TYPES
//Loosely related types
protocol Blendable {
func blend()
}
class Fruit: Blendable {
var name : String
init(name: String) {
self.name = name
}
func blend() {
print("i mush")
}
}
class Dairy {
var name : String
init(name: String) {
self.name = name
}
}
class Cheese: Dairy {}
class Milk: Dairy, Blendable {
func blend() {
print("mil")
}
}
func makeSmoothie(with ingredients: [Blendable]) {
for ingredient in ingredients {
ingredient.blend()
}
}
let milk = Milk(name: "milj")
makeSmoothie(with: [milk])
let strawberry = Fruit(name: "strwberry")
let cheddar = Cheese(name: "cheddar")
let chocoloate = Milk(name: "chocolate")
let ingredients: [Blendable] = [strawberry, chocoloate]
makeSmoothie(with:ingredients)
///PROTOCOL CODE CHALLENGE
// Declare protocol here
protocol ColorSwitchable {
func switchColor(_ color:Color)
}
enum LightState {
case on
case off
}
enum Color {
case rgb(Double, Double, Double, Double)
case hsb(Double, Double, Double, Double)
}
class WifiLamp: ColorSwitchable {
let state: LightState
var color: Color
init() {
self.state = .on
self.color = .rgb(0,0,0,0)
}
func switchColor(_ color: Color) {
self.color = color
}
}
//PROTOCOL EXAMPLE OF APPLE
//Step 1 create the protocol
protocol RandomNumberGenerator {
func random() -> Double
}
//step 2 create a class that adopts the protocol
class LinearCongruentialGenerator: RandomNumberGenerator {
var lastRandom = 42.0
let m = 139968.0
let a = 3877.0
let c = 29573.0
//implement the method gived by the protocol
func random() -> Double {
lastRandom = ((lastRandom * a + c).truncatingRemainder(dividingBy:m))
return lastRandom / m
}
}
let generator = LinearCongruentialGenerator()
print("Here's a random number: \(generator.random())")
// Prints "Here's a random number: 0.37464991998171"
print("And another one: \(generator.random())")
// Prints "And another one: 0.729023776863283"
//creating a class with a property of protocol type
class Dice {
let sides: Int
//step 3 this is the property
let generator: RandomNumberGenerator
init(sides: Int, generator: RandomNumberGenerator) {
self.sides = sides
self.generator = generator
}
func roll() -> Int {
//step 4 now that we have a protocoltype as a parameter we can access to its methods like this
//HERE THE PROTOCOL METHOD IS Random()
return Int(generator.random() * Double(sides)) + 1
}
}
//d6 is an instance of Dice class
var d6 = Dice(sides: 6, generator: LinearCongruentialGenerator())
for _ in 1...5 {
print("Random dice roll is \(d6.roll())")
}
//PROTOCOL INHERITANCE
protocol Printable {
func description() -> String
}
protocol NotSoPrettyPrintable {
func notsoprettydescription() -> String
}
//protocol inherited form more than one protocols
protocol PrettyPrintable: Printable, NotSoPrettyPrintable {
func prettyDescription() -> String
}
//structs can adopt more than one protocol
// structs needs to satisfy the requirements of the protocol and all the requirements of the protcols that the protocol adopted was inherit from
struct Player: PrettyPrintable, Equatable{
let name: String
let age: Int
let address: String
func description() -> String {
return "\(name) \(age) \(address)"
}
func prettyDescription() -> String {
return "name: \(name)\nage: \(age)\naddress: \(address)"
}
func notsoprettydescription() -> String {
return name
}
static func ==(lhs:Player, rhs:Player) -> Bool {
return lhs.name == rhs.name && lhs.age == rhs.age && lhs.address == rhs.address
}
}
let player = Player(name: "james", age: 33, address: "elpulgar")
player.description()
print(player.prettyDescription())
player.notsoprettydescription()
let otherPlayer = Player(name: "james", age: 33, address: "elpulgar")
player == otherPlayer
//EQuatable is a swift library protocol example "cando"
//CODING CHALLENGE EXAMPLE
protocol Animal {
var numberOfLegs: Int { get }
}
protocol Pet: Animal {
var cuddlyName: String { get }
}
struct Dog: Pet {
var numberOfLegs: Int
var cuddlyName: String
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment