35:swift父类与子类的转化(as! 强制转化)

class ClassViewController: UIViewController {
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view.
        // 1.子类对象转化为父类对象
        let food_Apple: Food = Apple(footName: "Apple")
        food_Apple.Nickname()
        let food_Coke: Food = Coke(footName: "Coca-Cola")
        food_Coke.Nickname()
        // 如果我们需要将当前父类对象转为子类对象但是并不确定 当前对象是否为子类对象转化过来的,该如何处理? Swift为我们提供一个方法 as?
        if let a = food_Apple as? Apple {
            a.footType = "Green foot"
            a.Nickname()
            print("子类对象")
        } else {
            print("非子类对象")
        if let a1 = food_Coke as? Coke {
            a1.footType = "Junk food"
            a1.Nickname()
            print("子类对象")
        } else {
            print("非子类对象")
        // 3 如何判断某一个对象是不是这个类的对象 可以 使用 对象 is 类 来判断
        // 我们会发现判断子类对象是不是父类对象返回也是true
        print(food_Apple is Apple)
    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
class Food {
    var name = ""
    init(footName: String) {
        name = footName
    func Nickname() {
        print("I am an \(name)")
class Apple: Food {
    var footType = ""
    override func Nickname() {
        print("I am an \(name),I tried \(footType) ")
class Coke: Food {
    var footType = ""
    override func Nickname() {
        print("I am an \(name),I tried \(footType) ")