Swift Journey (iv) objects and classes

Source: Internet
Author: User

To define a class, simply add the class name after class. Defining a property in a class is the same as defining a constant and variable, except that it is in the scope of the class. Similarly, the definition of a method and the definition of a function are the same.

class Shape {    var0    func simpleDescription() -> String {        return"A shape with \(numberOfSides) sides."    }}

Give it a try.

Add a constant attribute with let and a method with a parameter.

To create an instance of a class, simply add parentheses to the class name. Use a period to access the properties and methods of the class instance.

var7var shapeDescription = shape.simpleDescription()

This version of the Shape class is also a bit less important: the initializer (Bo main note: is actually a constructor), used to build the class when the class instance is created. denoted by init.

class NamedShape {    varnumberOfSides0    varname: String    init(name: String) {        self.name = name    }    func simpleDescription() -> String {        return"A shape with \(numberOfSides) sides."    }}

Notice how self is used to pass the name parameter to the Name property. When you create an instance of a class, the parameter is passed to the initializer as if it were called the function simultaneous parameter. Each property needs to specify a value-either at the time of definition (like numberofsides) or in the initializer (like name).

If you want to do some cleanup before the object is freed, you can use Deinit to create a destructor.

To define a subclass, simply add a semicolon after the class name, and then write the class name of the parent class. Swift does not require a class to inherit any standard parent class, so you can omit the parent class if necessary.

Subclasses the method to override the parent class needs to be tagged with override--if the method of overriding the parent class is not overridden, the compiler will get an error. The compiler will also detect if the override method is really a method of overriding the parent class.

Class Square:namedshape {varSidelength:double Init (sidelength:double, Name:String) { Self.Sidelength=Sidelength Super.Init (name:name) numberofsides= 4} func Area () -Double {returnSidelength*Sidelength} override func Simpledescription () -String{return "A square with sides of length \ (sidelength)."}} LetTest=Square (sidelength:5.2, Name:"My Test Square") test.Area () test.Simpledescription ()

Give it a try.

Add a Namedshape circle, with a RADIUS attribute, and receive the parameter in the initializer. Implement an area () and Simpledescription () method in the Circle class.

In addition to simple storage values, attributes can also be added getter and setter.

 class equilateraltriangle: namedshape {    varSidelength:double =0.0Init (sidelength:double, name:string) {self.sidelength = SidelengthSuper. Init (name:name) Numberofsides =3}varperimeter:double {Get{return 3.0* Sidelength}Set{sidelength = newvalue/3.0}    }OverrideFunc simpledescription (), String {return "an equilateral triangle with sides of length \ (sidelength)."}}varTriangle = Equilateraltriangle (sidelength:3.1, Name:"a triangle") println (triangle.perimeter) Triangle.perimeter =9.9println (Triangle.sidelength)

In the perimeter setter, the new value has a name that is implicitly called newvalue. You can explicitly define a name by enclosing the set with a parenthesis.

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

Sets the property value defined by the subclass.
Invokes the initializer of the parent class.
Change the property value defined by the parent class.
The rest of the initialization work for methods, getter, or setter can also be done at this time.
If you do not need to calculate the property value but still want to run a piece of code before or after you set the new value, you will use Willset and Didset. For example, the following class ensures that the side length of the triangle is consistent with the square edge length.

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 = Equila Teraltriangle (Sidelength:size, name:name)}}var triangleandsquare = triangleandsquare (Size:Ten, Name:"Another test shape") println (Triangleandsquare. Square. Sidelength) println (Triangleandsquare. Triangle. Sidelength) Triangleandsquare. Square= Square (sidelength: -, Name:"Larger square") println (Triangleandsquare. Triangle. Sidelength)

There is a very important difference between a method and a function in a class. Parameter names in functions can only be used within functions, but the parameter names in the method are also used when you call the method (except for the first argument). By default, the method call is the same as the method's own interior, and the parameter name is the same. You can then specify another 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 you encounter an optional value, you can write the method, the property, and the subscript before the operation. If? Before the value is nil, then? Everything after it is ignored, and the value of the entire expression is nil. Otherwise, the optional value is turned on,? After all the things follow the open value to continue. In either case, the value of the entire expression is an optional value.

let2.5"optional square")let sideLength = optionalSquare?.sideLength

Swift Journey (iv) objects and classes

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.