Ivars
@dynamicMemberLookup
public struct Ivars<IvarType>
A wrapper around an object for accessing ivars on it.
This type supports dynamic member lookup, which means that ivars can be accessed as if they were members of the type. Note that if an ivar with the given name does not exist, the dynamic member access will result in a crash.
To access a pointer to the ivar instead, use
Ivars.withIvar(_:_:)
.To fail gracefully if the ivar does not exist, use
Ivars.subscript(safelyAccessing:)
.To access an ivar with a name that clashes with an actual member on this type, it is possible to use
Ivars.subscript(dynamicMember:)
directly.
Example
let object = MyObject(foo: 5)
Ivars<Int>(object)._foo // 5
Ivars(object)._foo = 7
print(object.foo) // 7
-
Construct a new instance of
Ivars
for accessing instance variables onobject
.Declaration
Swift
public init(_ object: AnyObject)
Parameters
object
The object on which ivars are to be accessed.
-
Access an instance variable on the object.
It is safe to assume that
body
will be called on all execution paths.Warning
Thepointer
argument should not be stored and used outside of the lifetime of the call to the closure.Declaration
Swift
public func withIvar<Result>( _ name: String, _ body: (_ pointer: UnsafeMutablePointer<IvarType>?) throws -> Result ) rethrows -> Result
Parameters
name
The name of the instance variable to access.
body
A block which receives a pointer to the ivar, within which it may be read or written to.
pointer
The pointer to the ivar, or
nil
ifobject
does not have an ivar with the providedname
.Return Value
The value returned from
body
. -
Access an instance variable on the object, failing gracefully if the instance variable does not exist.
Note
If the setter is passed a value of
nil
, it will do nothing.Declaration
Swift
public subscript(safelyAccessing ivarName: String) -> IvarType? { get nonmutating set }
Parameters
ivarName
The name of the instance variable to access.
Return Value
The value of the instance variable, or
nil
if there is no ivar with the given name. -
Access an instance variable on the object.
Precondition
The ivar
ivarName
must be present on the object. If an ivar with the given name is not present, using this subscript will result in a crash.To fail gracefully, use
Ivars.subscript(safelyAccessing:)
orIvars.withIvar(_:_:)
.Declaration
Swift
public subscript(dynamicMember ivarName: String) -> IvarType { get nonmutating set }
Parameters
ivarName
The name of the instance variable to access.