Last active
November 13, 2020 05:29
-
-
Save akkyie/19f05166b3ce3398866cfaa140d96b7e to your computer and use it in GitHub Desktop.
This file contains hidden or 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
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