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

274
Visualizações
How can I get specific instance when I use static method

I hope to get a specific instance when I use my static method. For example:

class Food: NSObject {
    var name: String

    class func initFruit() -> Food? {
        let fruitName = NSStringFromClass(self).components(separatedBy: ".").last! as String

        if "Apple" == fruitName {
            return Apple(name: fruitName)
        } else if "Orange" == fruitName {
            return Orange(name: fruitName)
        }
        return nil
    }

    init(name: String) {
        self.name = name
    }

}

class Apple: Food {
}
class Orange: Food {
}

When I create an Apple instance with the method:

let apple = Apple.initFruit() as? Apple

How can I get the specific instance apple rather than use as? Apple?. I wonder how to modify the method:

 static func initFruit() -> Food?
over 4 years ago · Santiago Trujillo
3 Respostas
Responde à pergunta

0

There are a couple of problems with your design, let me try and enumerate them:

  • base classes should not be aware of their subclasses, it's bad practice and it's not scalable, as adding a new subclass would require maintaining the base class method
  • the static method is not needed at all, at least in the shape it's written in the question, you could simply directly call the initializers for the subclasses

Leaving all those aside, you can use Self as return type for the static method, this will allow dynamic results.

class Food: NSObject {
    var name: String

    class func initFruit() -> Self {
        let fruitName = NSStringFromClass(self).components(separatedBy: ".").last! as String

        return self.init(name: fruitName)
    }

    required init(name: String) {
        self.name = name
    }

}

class Apple: Food {
}
class Orange: Food {
}

let apple = Apple.initFruit() // is an Apple, no cast needed
over 4 years ago · Santiago Trujillo Relatório

0

i think it's not good idea because Food is parent class and Apple inherits Food. Apple may know it's parent class cause is extends Food but Food does not.

So, if you want to create instance by some string or some variable. I would like to recommend you to adopt "Factory pattern"

reference here: https://medium.com/swift-programming/design-patterns-creational-patterns-factory-pattern-in-swift-d049af54235b

over 4 years ago · Santiago Trujillo Relatório

0

Inspired by the question Generics in Swift - "Generic parameter 'T' could not be inferred I find another way to resolve this question. I add a method to infer the specific type.

func ascertainFruitType<T>() -> T {
    return self as! T // as! is dangerous
}

Then the method initFruit is changed on below:

class func initFruit() -> Self {
    let fruitName = NSStringFromClass(self).components(separatedBy: ".").last! as String

    if "Apple" == fruitName {
        return Apple(name: fruitName).ascertainFruitType()
    } else {
        return Orange(name: fruitName).ascertainFruitType()
    }

}
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