I get ObjC code with a lot of constructs like this:
in header file:
#import <Cocoa/Cocoa.h>
@interface AAPLView : NSView
{
NSImage *image;
}
@property(strong) NSImage *image;
@end
in implementation:
- (NSImage *)image {
return image;
}
- (void)setImage:(NSImage *)newImage {
if (image != newImage) {
image = newImage;
[self setNeedsDisplay:YES];
}
}
How to port in swift ?
If I write :
import Cocoa
class AAPLView: NSView {
var image : NSImage? {
get {
return self.image
}
set (newImage) {
if (image != newImage) {
self.image = newImage;
self.needsDisplay = true
}
}
}
I get an infinite loop on get as self.image calls itself repeatidly (why not the problem in ObjC ?)
So I write :
import Cocoa
class AAPLView: NSView {
var image : NSImage? {
didSet (newImage) {
if (image != newImage) {
self.image = newImage;
self.needsDisplay = true
}
}
}
What about the getter in this case ?
- (NSImage *)image {
return image;
In fact my code is pure Swift, no ObjC inside (ObjC is the sample code from WWDC than I am trying to port to Swift).
If the sample code I'm seeing is near enough to the WWDC code, The `AAPLSlide` inherits `NSCollectionViewItem`, and I believe you have not rewritten NSCollectionViewItem (or its ancestor classes) in Swift. So, your code in Swift needs to interact with classes written in Objective-C.
super refers to the var "selected" in ancestor class that I override ?
Yes.
The property `selected` is declared in NSCollectionViewItem class header as:
@property (getter=isSelected) BOOL selected;
Objective-C compiler interprets it as:
- in the private ivar section
BOOL _selected;
- and accessor methods
- (BOOL)isSelected;
- (void)setSelected:(BOOL)selected;
So, if `setSelected` is overridden in the Objective-C code, only setter of the property is overridden.
As you know, Swift cannot override only setter, so you need to keep getter as defined in the ancestor class, that is the part:
get {
return super.selected
}
and it internally calls supeclass's getter `isSelected` as Objective-C method.