Skip to content

Instantly share code, notes, and snippets.

@jose-ibanez
Last active March 3, 2016 00:46
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save jose-ibanez/c813f10d301c0e2b54be to your computer and use it in GitHub Desktop.
Save jose-ibanez/c813f10d301c0e2b54be to your computer and use it in GitHub Desktop.
Swift @NSCopying
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
@tkreuder
Copy link

tkreuder commented Oct 5, 2015

Values set during initialization are not cloned. You have to make var foo an optional and assign initialFoo to it in order to get a copy.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment