Passing struct in Swift
Struct are passed by values than by reference in Swift. So when assigning a new struct, it really is passing by value, so you need to access the original struct to modify the value.
struct Town {
var population = 1234
mutating func updatePopulation(newPopulation: Int) {
print("Updating population to \(newPopulation)")
population = newPopulation
print("Population has been updated to \(population)")
}
func describeTown() {
print("the town now has population of \(population)")
}
}
var orangeCounty = Town()
orangeCounty.updatePopulation(100)
orangeCounty.describeTown()
var yorkCountry = orangeCounty
yorkCounty.updatePopulation(50)
yorkCounty.describeTown()
# the town now has population of 100
# Updating population to 50
# Population has been updated to 100
# the town now has population of 100
Written by Angela
Related protips
Have a fresh tip? Share with Coderwall community!
Post
Post a tip
Best
#Swift
Authors
Related Tags
#swift
Sponsored by #native_company# — Learn More
#native_title#
#native_desc#