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

273
Views
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 answers
Answer question

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 Report

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 Report

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 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!