Add a variable to a class instance at runtime: Difference between revisions
Content added Content deleted
(added swift) |
|||
Line 1,368: | Line 1,368: | ||
x: 10 |
x: 10 |
||
10</pre> |
10</pre> |
||
=={{header|Swift}}== |
|||
We can use the same associated object mechanism as in Objective-C: |
|||
<lang swift>import Foundation |
|||
var fooKey: UnsafePointer<()> = nil |
|||
withUnsafePointer(&fooKey) { ptr in |
|||
fooKey = UnsafePointer<()>(ptr) |
|||
} // one way to define a unique key is a pointer variable that points to itself |
|||
class MyClass { } |
|||
let e = MyClass() |
|||
// set |
|||
objc_setAssociatedObject(e, fooKey, 1, objc_AssociationPolicy(OBJC_ASSOCIATION_RETAIN)) |
|||
// get |
|||
if let associatedObject = objc_getAssociatedObject(e, fooKey) { |
|||
println("associated object: \(associatedObject)") |
|||
} else { |
|||
println("no associated object") |
|||
}</lang> |
|||
=={{header|Tcl}}== |
=={{header|Tcl}}== |