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

263
Visualizações
Passing a Swift protocol to an Objective-C pointer

Using XCode 10.1 / Swift 4.2.

I'm trying to assign an object that conforms to a Swift protocol to an Objective-C pointer. The following code is a minimal example that compiles and works as expected, but it gives me the following warnings:

If assigning to a local variable: Incompatible pointer types initializing 'NSObject<Animal> *__strong' with an expression of type 'id<Animal> _Nullable'

If assigning to a stored property: Incompatible pointer types assigning to 'NSObject<Animal> *' from 'id<Animal> _Nullable'

Any idea on how to address that warning without just silencing it?

Swift code:

@objc protocol Animal {
    var name: String { get }
}

@objc class Pig: NSObject, Animal {
    var name: String = "pig"
}

@objc class Cow: NSObject, Animal {
    var name: String = "cow"
}

@objc class Farm: NSObject {
    static func getAnimal(name: String) -> Animal? {
        // return some animal or nil
    }
}

Objective-C code:

// This code returns a valid pointer to a Pig object
// that is usable in objective-c, but it also triggers 
// the warning described above
NSObject<Animal>* animal = [Farm getAnimalWithName:@"pig"];
over 4 years ago · Santiago Trujillo
1 Respostas
Responde à pergunta

0

Specify that every Animal implementer also implements NSObject's interface: @objc protocol Animal : NSObjectProtocol

You could also change the type of the variable in ObjC to id<Animal>.

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