Swift class, inheritance, interface, swift class inheritance Interface
Import Foundationclass Hello {var _ name: String? = "Swift global" init (name: String) {// constructor with parameters in the definition class _ name = name; println ("Hello, \ (name )");} init () {// constructor without parameters in the definition class println ("this is init method");} func sayHello () {// define the member method println ("hello \ (_ name)")} class func meClass () {// defines the class method println ("this is class method") ;}} class Hi: Hello {override func sayHello () {// inherits the Hello class, and reload its member method super. sayHello () // call the method println ("hloo override \ (_ name)") ;}} class HiChild: hi {} // inherits the Hi class extension Hi {// dynamically extends the Hi class, adds a member method, inherits the Hi class subclass, you can also call this method func sayHaha () {println ("HHHaaa") ;}} var h1 = Hello () // instance Hello class, call the init method without callback, and outputThis is init method
Var h2 = Hello (name: "Hello init") // call the init method with parameters. The output is as follows:Hello, Hello init
Var hi = Hi () // instantiate the subclass. The non-Attention constructor of the parent class is called and the outputThis is init method
Hi. sayHello () // call the class method and OutputHello Optional ("swift global") andHloo override Optional ("swift global ")
Var h3 = HiChild () // instantiate, call the constructor of the parent class, and outputThis is init method
H3.sayHaha () // if the parent class extends a method, its subclass can call this method and output HHHaaa
H3.sayHello () // call the method of the parent class and OutputHello Optional ("swift global") andHloo override Optional ("swift global ")
Hello. meClass () // call class method, outputThis is class method
Interface
Protocol People {// protocal defines an interface func getName ()-> String // declares a method in the interface. This method returns a String} class Man: people {// the class that implements this interface func getName ()-> String {// the class that implements the interface must implement all the methods in the interface return "zhangsan"} var m = Man () println ("Name is \ (m. getName ())")