Swift Chinese Tutorial (v) Objects and classes

Source: Internet
Author: User
Tags constant constructor count

Class classes

In Swift, you can create a class with the Class keyword followed by its name. In a class, the declaration of a property is the same as the declaration of a constant or variable, except that the attribute is in the context of the class, otherwise the method and function are written in the same way:

Class Shape {  
    var numberofsides = 0  
    func simpledescription ()-> String {return  
        "A-shape with \" (Numberofsid ES) sides. "
    }  
}

Practice:

Add a constant property with the Let keyword and add another method to receive the parameters.

Add parentheses after the class name to create an instantiation of the class, using the. (dot connector) to access the methods and properties of the instance:

1 var shape = shape ()
2 Shape.numberofsides = 7
3 var shapedescription = Shape.simpledescription ()

This version of the shape class lacks an important thing: the constructor-the setting after the class is created. You can use Init to create a:

Class Namedshape {  
    var numberofsides:int = 0  
    var name:string  
         
    init (name:string) {  
        self.name = name
  
     
         
    func simpledescription ()-> String {return  
        ' A shape with \ (numberofsides) sides.}  
}
  

Note that self here is used to differentiate between the name parameter and the name attribute in the constructor. When you create an instance of a class, the parameter passing in the constructor is the same as the parameter pass form of the function. Each property needs to specify a value for it, either in the declaration (such as Nameofsides) or within the constructor (such as name).

Use Deinit to create a destructor to perform cleanup work on Object destruction.

Inheritance and polymorphism

Subclasses can be followed by a colon directly with the superclass name, the subclass declaration does not need to make any standard base class, so the superclass class can be ignored.

A subclass method overrides or overloads the implementation in the superclass to add the override tag, otherwise the compiler will complain, and the compiler will also detect whether the overloaded method marked as override has been overwritten to the superclass.

Class Square:namedshape {//To take an example, Namedshape is the superclass  
    var sidelength:double  
         
    init (sidelength:double, name:string) { C3/>self.sidelength = Sidelength  
        super.init (name:name)  
        numberofsides = 4  
    }  
         
    func area ()->  Double {return  
        sidelength * sidelength  
    }  
         
    override func simpledescription ()-> String {// This is where you use override to overload the method of superclass namespace in the previous case simpledescription  
	//View more highlights in this column: Http://www.bianceng.cn/Programming/extra /return
        "A square with sides of length \ (sidelength)."
    }  
Let test = Square (sidelength:5.2, name: ' My Test Square ')  
Test.area ()  
test.simpledescription ()

Practice:

Write another subclass of Namedshape: Circle, incoming radii and names as parameters to their constructors, and implement the area and describe methods in the Circle class.

In addition, a declared property usually has a get and a set method:

Class Equilateraltriangle:namedshape {  
    var sidelength:double = 0.0  
         
    init (sidelength:double, name:string) {
  
   self.sidelength = Sidelength  
        super.init (name:name)  
        numberofsides = 3  
    }  
         
    var perimeter:double {  
    get {return  
        3.0 * Sidelength  
    }  
    set {  
        sidelength = newvalue/3.0  
    }  
    }  
         
    override Func Sim Pledescription ()-> String {return  
        "a equilateral triagle with sides of length \ (sidelength)."
    }  
var triangle = equilateraltriangle (sidelength:3.1, Name: "a triangle")  
triangle.perimeter  
Triangle.perimeter = 9.9  
triangle.sidelength
  

In the example above, the default name for the value in the set of perimeter is newvalue, and you can then specify a different name for it in parentheses after the set.

Note that the constructor for the Equilateraltriangle class has three different steps:

The first step is to set the values of each attribute of the subclass;

The second step is to invoke the superclass constructor;

The third step is to change the value of the attribute defined in the superclass, and other methods, such as Get,set, can be implemented in this step.

If you do not need to compute the value of the property, but want to execute the code before or after setting the property value, you can use Willset (before) and Didset (after). Class in the following example--make sure that the edges of the triangle is always equal to the length of the rectangular edge:

Class Triangleandsquare {  
    var triangle:equilateraltriangle {  
    Willset {  
        square.sidelength = Newvalue.sidelength  
    }  
    }  
    var square:square {  
    Willset {  
        triangle.sidelength = Newvalue.sidelength  
    }  
    }  
    Init (size:double, name:string) {  
        square = Square (sidelength:size, name:name)  
        triangle = Equilateraltriangle (Sidelength:size, Name:name)  
    }}  
var triangleandsquare = Triangleandsquare (size:10, Name: "Another Test shape")  
TriangleAndSquare.square.sideLength  
triangleAndSquare.triangle.sideLength  
triangleandsquare.square = Square (SIDELENGTH:50, name: "Larger square")  
TriangleAndSquare.triangle.sideLength

The method of a class has an important difference from a function: The parameter name of the function only works within this function, and the parameter name of the method can be used to invoke the method (except the first argument). By default, a method has an argument with the same name, and the method itself is invoked. You can specify a second name to use within the method:

Class Counter {  
    var count:int = 0  
    func incrementby (amount:int, Numberoftimes times:int) {  
        count + = Amount * Times  
    }  
}  
var counter = counter ()  
Counter.incrementby (2, Numberoftimes:7)

When working with an optional value (described in the IF statement in chapter III), you can write the "?" operator in front of the method or property. If the value is in the "?" It's been nil before, all after "?" is automatically ignored, and the entire expression is nil. In addition, the optional values are not encapsulated, and all "?" values are not encapsulated. In both cases, the value of the entire expression is an optional value:

1 Let Optionalsquare:square? = Square (sidelength:2.5, name: "Optional Square")//? Optional values are described in chapter III of the IF statement section
2 Let Sidelength = Optionalsquare? Sidelength

Author: cnblogs Joe.huang

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.