1, first look at how to define the properties, constructors, methods, and class methods within a class and class in Swift
Import Foundationclasshello{//member Propertiesvar _name:nsstring?="Jikexueyuan" //constructor Functioninit () {}//Overloaded ConstructorsInit (name:nsstring) {_name=name}//Methodfunc SayHello () {println ("Hello \ (_name)") } //class Method classfunc Sayhi () {println ("Hello Swift")}}var Hello= Hello (Name:"Chen") Hello.sayhello () Hello.sayhi ()
2, inheritance in Swift is expressed in the form of a colon, as in C #. Once a class inherits its parent class, it has both the properties and methods of the parent class. You can override a method of a parent class in a subclass, or you can call a method of a parent class.
class Hi:hello { // overrides the parent class method override func SayHello () { Super.sayhello ( )// Call the parent class method println ("Hi \ (_name)") = Hi () Hi.sayhello ()
3, in the process of programming, sometimes we use the third-party class library or the use of the system's class library, it is found that some classes in these libraries need to expand the use of extension keyword can be implemented. If the subclass inherits the parent class with the extension extension, the corresponding subclass should also have an extended method.
// dynamic extension of a class extension hi{ func Sayhaha () { println ("Haha") }}hi.sayhaha ()
4, in Swift, the interface uses the Protocol keyword to define
protocol person{ func getName ()nsstring}class Man:person { nsstring { return"Jikexueyuan" = = Hi (name:man.getName ()) Himan.sayhello ()
5, in Swift, namespaces are implemented using nested methods of classes, but when namespaces are nested complex and namespaces have very many classes, they become bloated. This time you can define the namespace nesting in a swift file, use the extension keyword in another swift file to extend the namespace, and then call it directly in the file you are using.
//---space.swiftclasscom{classjikexueyuan{}}//---hello.swiftextension com.jikexueyuan{classHello {func SayHello () {println ("Hello") } }}//---hi.swiftextension com.jikexueyuan{classHi {func sayhi () {println ("Hi") } }}//---main.swiftvar Spacehello =Com.jikexueyuan.Hello () Spacehello.sayhello () var Spacehi=com.jikexueyuan.Hi () spacehi.sayhi ( )
Swift Object-oriented explanation