Jump to content

Add a variable to a class instance at runtime: Difference between revisions

added swift
(added swift)
Line 1,368:
x: 10
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}}==
Anonymous user
Cookies help us deliver our services. By using our services, you agree to our use of cookies.