-
-
Save mitchellporter/4d00a3043f7ef357f238 to your computer and use it in GitHub Desktop.
Swift @NSCopying
This file contains hidden or 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 UIKit | |
| /* | |
| I'm not sure why `@NSCopying` doesn't seem to be copying the object in the example below. | |
| I'm attempting to write code that follows the "initialization with a configuration object" pattern, like `NSURLSession`. | |
| Ideally the configuration would be a struct, but since I'm still interoperating with Obj-C that's not an option. | |
| */ | |
| class Foo : NSObject, NSCopying { | |
| var bar = "bar" | |
| var baz = 1 | |
| func copyWithZone(zone: NSZone) -> AnyObject { | |
| let copy = Foo() | |
| copy.bar = bar | |
| copy.baz = baz | |
| return copy | |
| } | |
| } | |
| class Test : NSObject { | |
| @NSCopying private(set) var foo : Foo | |
| init(foo : Foo) { | |
| self.foo = foo | |
| super.init() | |
| } | |
| } | |
| var initialFoo = Foo() | |
| initialFoo.bar = "initial" | |
| initialFoo.baz = 0 | |
| let test = Test(foo: initialFoo) // `test`'s version of `foo` should be a copy of `initialFoo` | |
| test.foo.bar // "initial" | |
| test.foo.baz // 0 | |
| var readFoo = test.foo // `readFoo` should be a copy of `test`'s copy of `initialFoo` | |
| initialFoo === readFoo // true | |
| readFoo.bar = "changed" | |
| readFoo.baz = 100 | |
| test.foo.bar // "changed" | |
| test.foo.baz // 100 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment