Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

171
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda