我希望在使用静态方法时得到一个特定的实例.例如: class Food: NSObject { var name: String class func initFruit() - Food? { let fruitName = NSStringFromClass(self).components(separatedBy: ".").last! as String if "Apple"
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 { }
当我使用以下方法创建Apple实例时:
let apple = Apple.initFruit() as? Apple
如何获取特定实例苹果而不是用作?苹果?.我想知道如何修改方法:
static func initFruit() -> Food?您的设计存在一些问题,让我尝试枚举它们:
>基类不应该知道它们的子类,这是不好的做法而且它不可扩展,因为添加一个新的子类需要维护基类方法
>根本不需要静态方法,至少在问题中写的形状中,你可以简单地直接调用子类的初始化器
抛开所有这些,你可以使用Self作为静态方法的返回类型,这将允许动态结果.
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