[Swift] Be aware of different behaviour between struct and class
This file contains 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
import Foundation | |
class Cat: CustomStringConvertible { | |
var description: String { | |
return "\(name): \(age) years old" | |
} | |
let name: String | |
var age: Int | |
init(name: String = "Sue", age: Int = 0) { | |
self.name = name | |
self.age = age | |
} | |
} | |
struct Dog: CustomStringConvertible { | |
var description: String { | |
return "\(name): \(age) years old" | |
} | |
let name: String | |
var age: Int | |
init(name: String = "Sue", age: Int = 0) { | |
self.name = name | |
self.age = age | |
} | |
} | |
var cats = Array<Cat>(repeating: Cat(), count: 2) | |
cats[1].age = 2 | |
var dogs = Array<Dog>(repeating: Dog(), count: 2) | |
dogs[1].age = 2 | |
print("cats: \(cats)") | |
print("dogs: \(dogs)") | |
/* | |
output: | |
cats: [Sue: 2 years old, Sue: 2 years old] | |
dogs: [Sue: 0 years old, Sue: 2 years old] | |
*/ |
References
- Swift - Classes and Structures#Classes Are Reference Types
댓글
댓글 쓰기