class Owner {
var name: String
init(name: String) {
self.name = name
}
}
let sergey = Owner(name: "Sergey")
let richard = sergey
richard.name = "Richard"
print(sergey.name) // Richard
print(richard.name) // Richard
var owner = Owner(name: "Thanos")
print(isKnownUniquelyReferenced(&owner)) // True. There is only one link on the instance
var newOwner = owner
print(isKnownUniquelyReferenced(&owner)) // False. Multiple links on the instance
let playerOne = PlayerClass(name: "One", health: 100, energy: 10)
let playerTwo = PlayerClass(name: "One", health: 100, energy: 10)
if (playerOne == playerTwo) {
print("Equal")
}
if (playerOne === playerTwo) {
print("Identical")
}
struct Stone {
enum `Type` {
case space
case mind
case reality
case power
case time
case soul
}
var type: Type // Enum - value type
let owner: Owner // Class - reference type
}
let spaceStone = Stone(type: .space, owner: Owner(name: "Elon"))
var spaceStone2 = spaceStone // Creating a copy
// Changing the values
spaceStone2.type = .mind
spaceStone2.owner.name = "Loki"
/**
# The value has NOT changed
*/
print(spaceStone.type) // Space
print(spaceStone2.type) // Mind
/**
# The value has changed.
*/
print(spaceStone.owner.name) // Loki
print(spaceStone2.owner.name) // Loki
var zeus = Owner(name: "Zeus")
var stone = Stone(type: .reality, owner: zeus)
func update(stone: inout Stone, owner: Owner) {
owner.name = "Vision"
stone.type = .time // Without `inout` we can't change it
}
update(stone: &stone, owner: zeus)
func oneMore(than number: Int) -> Int {
return number + 1
}
var myNumber = 1
myNumber = oneMore(than: myNumber)
print(myNumber)
// Prints "2"
var stepSize = 1
func increment(_ number: inout Int) {
number += stepSize
}
increment(&stepSize)
// Error: conflicting accesses to stepSize
One way to solve this conflict is to make an explicit copy of stepSize:
// Make an explicit copy.
var copyOfStepSize = stepSize
increment(©OfStepSize)
// Update the original.
stepSize = copyOfStepSize
// stepSize is now 2