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

353
Visualizações
Why Swift Int zero is read nil in objc code?

I'm working on a mixed objc and swift project, and I've noticed that when I have an Int property in a Swift class that has a value 0 when I read this value from Objc code it returns nil.

A Swift class with an integer property that is visible from ObjC:

@objc
class SwiftInt: NSObject {

    @objc let testInt: Int = 0
}

Now when I read this property in an Objc code, it says that testInt is nil:

- (void)viewDidLoad {
    [super viewDidLoad];
    SwiftInt *swiftInt = [SwiftInt new];
    if (swiftInt.testInt == nil) {
        NSLog(@"This shouldn't be nil");
    }
}

If I set any other number than 0, that value is correctly returned, but for 0 it returns nil. The question is why is this nil in Objc when Int is a primitive type and it's a non optional? I'm using Swift 4.2.

over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Because in Objective-C nil defined as __DARWIN_NULL:

#ifndef nil
# if __has_feature(cxx_nullptr)
#   define nil nullptr
# else
#   define nil __DARWIN_NULL
# endif
#endif

Which defined as (void *)0 in Obj-C

So your code:

if (swiftInt.testInt == nil) { ... }
if (0 == nil) { ... }
if (0 == 0) { ... }

Which is always true

Good article about nil in Obj-C http://benford.me/blog/the-macro-behind-nil/

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