Skip to content

Instantly share code, notes, and snippets.

@mitchellporter
Forked from jose-ibanez/NSCopying_test.swift
Created March 3, 2016 00:46
Show Gist options
  • Select an option

  • Save mitchellporter/4d00a3043f7ef357f238 to your computer and use it in GitHub Desktop.

Select an option

Save mitchellporter/4d00a3043f7ef357f238 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment