简体   繁体   中英

Swift: Is it possible that parent class class function returns a instance of subclass?

I wrote the Swift code below.

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

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.

You should downcast the object returned by getAnimalByName method,

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() . Return Animal , then you can use an optional downcast or a force downcast:

// 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM