Value Semantics
Returned Copy
A method can return an updated copy instead of changing the original value.
Build an updated value
returned_copy.swift
struct Settings {
var level: Int
func withLevel(_ nextLevel: Int) -> Settings {
var copy = self
copy.level = nextLevel
return copy
}
}
let selectedLevel =
let base = Settings(level: 0)
let updated = base.withLevel(selectedLevel)
let message = "base=\(base.level), updated=\(updated.level)"
print(message)
struct Settings {
var level: Int
func withLevel(_ nextLevel: Int) -> Settings {
var copy = self
copy.level = nextLevel
return copy
}
}
let selectedLevel =
let base = Settings(level: 0)
let updated = base.withLevel(selectedLevel)
let message = "base=\(base.level), updated=\(updated.level)"
print(message)
struct Settings {
var level: Int
func withLevel(_ nextLevel: Int) -> Settings {
var copy = self
copy.level = nextLevel
return copy
}
}
let selectedLevel =
let base = Settings(level: 0)
let updated = base.withLevel(selectedLevel)
let message = "base=\(base.level), updated=\(updated.level)"
print(message)
copied update
Returning a modified copy keeps the original value available for comparison.