Skip to content

Instantly share code, notes, and snippets.

@aainaj
Last active July 13, 2018 04:50
Show Gist options
  • Save aainaj/e29760368577bf5b41cb899482e415d7 to your computer and use it in GitHub Desktop.
Save aainaj/e29760368577bf5b41cb899482e415d7 to your computer and use it in GitHub Desktop.
Mutable Reference Type in Struct
import Foundation
class ProductFactory: NSObject, NSCopying {
var items = 8
func copy(with zone: NSZone? = nil) -> Any {
let factory = ProductFactory()
factory.items = items
return factory
}
}
struct Product {
let identifier: Int
let name: String
private var _factory = ProductFactory()
init(identifier: Int, name: String) {
self.identifier = identifier
self.name = name
}
var getFactory: ProductFactory {
return _factory
}
var setFactory: ProductFactory {
mutating get {
if !isKnownUniquelyReferenced(&factory) {
_factory = factory.copy() as! ProductFactory
}
return _factory
}
}
}
let productA = Product(identifier: 234, name: "electronics")
var productB = productA
productB.setFactory.items = 4
print("product A items \(productA.getFactory.items)")
print("product B items \(productB.getFactory.items)")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment