[フレーム]
Last Updated: March 03, 2016
·
5.048K
· angelathewebdev

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

AltStyle によって変換されたページ (->オリジナル) /