objective-cswiftnsrect

Populating NSRectPointer in Swift


I'm translating some Objective-C code I got from a book to Swift. The code in question is a custom implementation of an NSTextContainer method:

-(NSRect)lineFragmentRectForProposedRect:(NSRect)proposedRect
                          sweepDirection:(NSLineSweepDirection)sweepDirection
                       movementDirection:(NSLineMovementDirection)movementDirection
                           remainingRect:(NSRectPointer)remainingRect
{

 // ... now set value of the struct pointed at by NSRectPointer
 *remainingRect = NSRectMake(0, 0, 100, 50);

 //...
 return mainRect;
}

I struggling to replicate this in Swift - no matter what I try I keep getting told that I can't assign to a let variable.


Solution

  • NSRectPointer is defined as

    public typealias NSRectPointer = UnsafeMutablePointer<NSRect>
    

    and UnsafeMutablePointer has a

    /// Access the underlying raw memory, getting and setting values.
    public var memory: Memory { get nonmutating set }
    

    property, therefore the Swift equivalent of the Objective-C code

    *remainingRect = NSRectMake(0, 0, 100, 50);
    

    should be

    remainingRect.memory = NSMakeRect(0, 0, 100, 50)