[英]Swift: Is it possible that parent class class function returns a instance of subclass?
I wrote the Swift code below. 我在下面编写了Swift代码。
class Animal {
class func getAnimalByName(name:String) -> ?? {
if(name == "Cat") {
return Cat()
} else {
return Bird()
}
}
}
class Cat: Animal {
func run() {
println("run")
}
}
class Bird: Animal {
func fry() {
println("fry")
}
}
Then I want to write like below code without using "as Cat" casting 然后我想像下面的代码那样编写而不使用“ as Cat”强制转换
var cat = Animal.getAnimalByName(name: "Cat")
cat.run()
What should ?? 什么应该 ?? in Animal class be ?
在动物课上是?
I tried AnyObject but when I built the code on iphone simulator, I got an error saying "methodSignatureForSelector: -- trouble ahead Unrecognized selector -[Cat run]" though this compile successed. 我尝试了AnyObject,但是当我在iphone模拟器上构建代码时,出现了一个错误,提示“ methodSignatureForSelector:-提前遇到无法识别的选择器-[Cat运行]”,尽管此编译成功。
You should downcast the object returned by getAnimalByName
method, 您应该向下转换由
getAnimalByName
方法返回的对象,
class Animal {
class func getAnimalByName(name:String) -> Animal {
if(name == "Cat") {
return Cat()
} else {
return Bird()
}
}
}
class Cat: Animal {
func run() {
println("run")
}
}
class Bird: Animal {
func fry() {
println("fry")
}
}
var cat = Animal.getAnimalByName("Cat") as Cat
cat.run()
You can't do this without a downcast, since it will have to go from something to the particular type Cat
if you want to be able to call cat.run()
. 如果不进行向下转换,您将无法做到这一点,因为如果您希望能够调用
cat.run()
,它将必须从某种类型转换为特定类型的Cat
。 Return Animal
, then you can use an optional downcast or a force downcast: 如果返回Return
Animal
,则可以使用可选的向下转换或强制向下转换:
// optional
let cat = Animal.getAnimalByName("Cat")
if let cat = cat as? Cat {
cat.run()
}
// forced
let cat2 = Animal.getAnimalByName("Cat")
(cat2 as! Cat).run()
That said, don't do the second one, only do the optional cast. 也就是说,不要执行第二个,只执行可选的强制转换。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.