Skip to content

Instantly share code, notes, and snippets.

@akkyie
Last active November 13, 2020 05:29
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save akkyie/19f05166b3ce3398866cfaa140d96b7e to your computer and use it in GitHub Desktop.
Save akkyie/19f05166b3ce3398866cfaa140d96b7e to your computer and use it in GitHub Desktop.
struct Cow<Food> {
class Stomach {
var food: Food? = nil
func copy() -> Stomach {
let stomach = Stomach()
stomach.food = food
return stomach
}
}
var stomach = Stomach()
mutating func eat(_ food: Food) {
if !isKnownUniquelyReferenced(&stomach) {
stomach = stomach.copy()
}
stomach.food = food
}
}
class Grass {}
var grass1 = Grass()
var grass2 = Grass()
print("grass1 = 0x" + String(unsafeBitCast(grass1, to: Int.self), radix: 16))
print("grass2 = 0x" + String(unsafeBitCast(grass2, to: Int.self), radix: 16))
var cow1 = Cow<Grass>()
cow1.eat(grass1)
print("grass1 = 0x" + String(unsafeBitCast(cow1.stomach.food, to: Int.self), radix: 16))
var cow2 = cow1
print("grass1 = 0x" + String(unsafeBitCast(cow2.stomach.food, to: Int.self), radix: 16))
cow1.eat(grass2)
print("grass1 = 0x" + String(unsafeBitCast(cow2.stomach.food, to: Int.self), radix: 16))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment