Is there a naming convention that will allow Swift to automatically associate C functions that act on a struct with the struct itself?
For instance, CGRect is declare as following:
struct CGRect {
CGPoint origin;
CGSize size;
};
typedef struct CG_BOXABLE CGRect CGRect;
...
CG_EXTERN CGFloat CGRectGetMinX(CGRect rect)
CG_AVAILABLE_STARTING(10.0, 2.0);
But I can write Swift code like this:
let rect = CGRect()
let minX = rect.minX
I've attempted to copy the same in the hope that I could get the same behaviour from my own C structs, but can't seem to get it to work correctly.
Is this automatic behaviour due to exactly how the struct is declared, or is it added elsewhere via extensions / some other magic?
If it's via extensions, how do you disallow the original CGRectGetMinX function in Swift?
Swift 3 introduced the feature to import global functions as member functions, see SE-0044 Import as member.
Here is a simple example how you can use that for your own struct types:
typedef struct MyRect {
int x;
int y;
int w;
int h;
} MyRect;
// Import as computed property:
int MyRectGetMinX(MyRect rect)
__attribute__((swift_name("getter:MyRect.minX(self:)")));
// Import as method:
int MyRectArea(MyRect rect)
__attribute__((swift_name("MyRect.area(self:)")));
Now you can call it from Swift as
let rect = MyRect()
let mx = rect.minX
let ar = rect.area()
and using the global function fails to compile:
let mx = MyRectGetMinX(rect)
// Error: 'MyRectGetMinX' has been replaced by property 'MyRect.minX'
let ar = MyRectArea(rect)
// Error: 'MyRectArea' has been replaced by instance method 'MyRect.area()'