Skip to content

Instantly share code, notes, and snippets.

@seancatkinson
Created January 24, 2016 15:05
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save seancatkinson/9d859161bd0885631468 to your computer and use it in GitHub Desktop.
Save seancatkinson/9d859161bd0885631468 to your computer and use it in GitHub Desktop.
Final example code.
/**
A generic function that swaps to values of the same type
- parameter a: the value to placed in variable b
- parameter b: the value to be placed in variabe a
*/
func swapTwoValues <T>(inout a:T, inout _ b:T) {
let temp = a
a = b
b = temp
}
// Example Usage
var one = "Hello"
var two = "World"
swapTwoValues(&one, &two)
print(one) // World
print(two) // Hello
/**
Example usage of the array struct
*/
var numbers = [1,2,3,4,5]
// equivalent to:
var numbers2 : [Int] = numbers
// also equivalent to:
var numbers3 : Array<Int> = numbers2
/**
Generic Protocols
*/
protocol Eating {
typealias FoodType:Edible
func eat(food:FoodType)
}
extension Eating {
func eat(food:FoodType) {
print("Nom nom nom!")
}
}
protocol Edible {}
protocol Meaty : Edible {}
protocol Veggie : Edible {}
class DogFood : Meaty {}
class Lettuce : Veggie {}
protocol Cuddly {
func cuddle(cuddlee:Cuddly) // Using cuddle(cuddlee:Self) make this protocol Generic
func findCuddlePartner() -> Self
}
/**
Generic Types
*/
class Dog<Food : Meaty> : Eating {
typealias FoodType = Food
}
class Rabbit<Food : Veggie> : Eating {
typealias FoodType = Food
func snuggle(snugglee:Rabbit) {
// snuggle with the other bunny
}
}
let dog = Dog<DogFood>()
//let veggieDog = Dog<Lettuce>()
//let rabbit = Rabbit<DogFood>()
let dogfood = DogFood()
let lettuce = Lettuce()
dog.eat(dogfood)
//dog.eat(lettuce)
/**
Generic Type Constraints
*/
func feedRabbits<Food : Veggie>(rabbits:[Rabbit<Food>], food:Food) {
for rabbit in rabbits {
rabbit.eat(food)
}
}
class EatingThunk<Food:Edible> : Eating {
private let _eat : (food:Food)->()
init <Wrapped : Eating where Wrapped.FoodType == Food>(_ wrapped:Wrapped) {
_eat = wrapped.eat
}
func eat(food: Food) {
_eat(food: food)
}
}
//let eater : Eating = Dog<DogFood>() // nope
//let eater : Eating<DogFood> = Dog<DogFood>() // still nope
let eater : EatingThunk<DogFood> = EatingThunk(dog)
eater.eat(dogfood)
//eater.eat(lettuce) // no thanks
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment