Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

170
Views
Automatic bridging of C struct functions to Swift methods

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?

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

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()'
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!