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()




        // 2,父类对象转为子类对象 as!  as?

        // 父类对象转化为子类对象,父类转化为子类需要使用 as! 如果当前对象是父类对象,但是他如果是子类对象转化过来的,那么可以转化回去




        let apple = food_Apple as! Apple

        apple.footType = "Green foot"

        apple.Nickname()



        let coke = food_Coke as! Coke

        coke.footType = "Junk 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) ")

    }

}

你可能感兴趣的:(35:swift父类与子类的转化(as! 强制转化))