Swift Chinese tutorial (5) -- objects and Classes

Source: Internet
Author: User

  

 

  Class

 

In Swift, you can use the class keyword followed by the class name to create a class. In a class, the declaration of an attribute is the same as that of a constant or variable. Unless this attribute is in the context of the class, the method and function are also written as follows:

1 class Shape {2     var numberOfSides = 03     func simpleDescription() -> String {4         return "A shape with \(numberOfSides) sides."5     }6 }

Exercise:

Use the let keyword to add a constant attribute and add another method to receive parameters.

 

Add parentheses after the class name to create class instantiation. Use the. (DOT connector) to access the methods and attributes of the instance:

1 var shape = Shape()2 shape.numberOfSides = 73 var shapeDescription = shape.simpleDescription()

 

This version of the Shape class lacks an important thing: constructor -- the setting of the class after it is created. You can use init to create one:

 1 class NamedShape { 2     var numberOfSides: Int = 0 3     var name: String 4      5     init(name: String) { 6         self.name = name 7     } 8      9     func simpleDescription() -> String {10         return "A shape with \(numberOfSides) sides."11     }12 }

Note that self is used to differentiate the name parameter and name attribute in the constructor. When creating an instance of the class, the parameter transmission in the constructor is the same as the parameter transmission form of the function. Each attribute must be specified with a value, either in the Declaration (such as nameOfSides) or in the constructor (such as name ).

Use deinit to create a destructor to clear objects during destruction.

 

  Inheritance and Polymorphism

 

The subclass can be directly followed by a colon. When the subclass is declared, no standard base class is required. Therefore, the superclass after the subclass can be ignored.

Override should be added to the implementation of the method override or overload superclass of the subclass. Otherwise, the compiler will report an error and the compiler will check whether the overloaded method marked as override has overwritten the superclass.

 

1 class Square: NamedShape {// next example. NamedShape is a super class 2 var sideLength: Double 3 4 init (sideLength: Double, name: String) {5 self. sideLength = sideLength 6 super. init (name: name) 7 numberOfSides = 4 8} 9 10 func area ()-> Double {11 return sideLength * sideLength12} 13 14 override func simpleDescription () -> String {// override is used to reload the simpleDescription15 return "A square with sides of length \ (sideLength) method of the super class NameSpace in the previous example ). "16} 17} 18 let test = Square (sideLength: 5.2, name:" my test square ") 19 test. area () 20 test. simpleDescription ()

 

Exercise:

Write anotherSubclass of NamedShape:Circle, Pass in the radius and name as parameters to its constructor, and implement area andDescribe method.

  In addition, declared attributes usually have a get and a set method:

 1 class EquilateralTriangle: NamedShape { 2     var sideLength: Double = 0.0 3      4     init(sideLength: Double, name: String) { 5         self.sideLength = sideLength 6         super.init(name: name) 7         numberOfSides = 3 8     } 9     10     var perimeter: Double {11     get {12         return 3.0 * sideLength13     }14     set {15         sideLength = newValue / 3.016     }17     }18     19     override func simpleDescription() -> String {20         return "An equilateral triagle with sides of length \(sideLength)."21     }22 }23 var triangle = EquilateralTriangle(sideLength: 3.1, name: "a triangle")24 triangle.perimeter25 triangle.perimeter = 9.926 triangle.sideLength

  

In the preceding example, the default value of perimeter's set is newValue. You can specify other names in parentheses after set.

Note that the constructor of the EquilateralTriangle class has three different steps:

Step 1: Set the values of each attribute of the subclass;

Step 2: Call the hyperclass constructor;

Step 3: Change the attribute value defined in The superclass. Other methods, such as get and set, can be implemented in this step.

If you do not need to calculate the attribute value, but want to execute code before or after setting the attribute value, you can use willset (Before) and didset (after ). In the following example, make sure that the side length of the triangle is always equal to the side length of the rectangle:

 1 class TriangleAndSquare { 2     var triangle: EquilateralTriangle { 3     willSet { 4         square.sideLength = newValue.sideLength 5     } 6     } 7     var square: Square { 8     willSet { 9         triangle.sideLength = newValue.sideLength10     }11     }12     init(size: Double, name: String) {13         square = Square(sideLength: size, name: name)14         triangle = EquilateralTriangle(sideLength: size, name: name)15     }16 }17 var triangleAndSquare = TriangleAndSquare(size: 10, name: "another test shape")18 triangleAndSquare.square.sideLength19 triangleAndSquare.triangle.sideLength20 triangleAndSquare.square = Square(sideLength: 50, name: "larger square")21 triangleAndSquare.triangle.sideLength

 

There is an important difference between a class method and a function: the function parameter name only acts on this function, and the method parameter name can be used to call a method (except for the first parameter ). A method has a parameter with the same name. You can specify the second name and use it inside the method:

1 class Counter {2     var count: Int = 03     func incrementBy(amount: Int, numberOfTimes times: Int) {4         count += amount * times5     }6 }7 var counter = Counter()8 counter.incrementBy(2, numberOfTimes: 7)

 

Optional values (For details, refer toIf statement Introduction) When working together, you can write "? "Operator. If the value is "? "Previously nil, all in "? "Will be automatically ignored later, and the entire expression is nil. In addition, the optional values are unencapsulated. All "? "All subsequent values are unencapsulated values. In both cases, the value of the entire expression is optional:

1 let optionalSquare: Square? = Square (sideLength: 2.5, name: "optional square ")//? For more information about the optional values, see Chapter 3If statement2 let sideLength = optionalSquare ?. SideLength

 

 

 

Thank you, Swifter-QQ group: 362232993 ~

Github address: https://github.com/Joejo/Swift-lesson-for-chinese

 

 

  

 

 

 

 

 

 

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.