Last active
July 13, 2018 04:50
-
-
Save aainaj/e29760368577bf5b41cb899482e415d7 to your computer and use it in GitHub Desktop.
Mutable Reference Type in Struct
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 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