Welcome to Swift (Apple's official Swift document translation and annotations IV)---19~28 page

Source: Internet
Author: User

In Swift, a function is actually a special composition (closure), you can also define an anonymous composition (closure), write the code in ({}), and use in to separate parameters and return values.

Numbers.map ({

(Number:int), Int in

Let result = 3 * number

return result

})

  Experiment//Exercises

  Rewrite the closure to return zero for all odd numbers. Rewrite writes a composition that returns a value of 0;

For more precise use of the composition (closures), you can have several options. When the type is explicit, such as the proxy's callback function, you can omit the type of its arguments, and the return value type. The combination of a single statement that implicitly returns the value of its execution statement.

Numbers.map ({number in 3 * number})

The designation of a parameter uses a number instead of a name, which is particularly useful for very short compositions (closures). When a composition (closure) is passed as the last parameter of a function, it can be immediately followed by ().

Sort ([1, 5, 3, 2]) {$ > $}

Objects and Classes

/* Objects and classes */

In Swift, you create a class by using the Class keyword plus its name. The member/attribute declaration methods in a class are the same as the previous constant/variable declarations, except that they must be within the definition of the class. The same is true for methods and functions.

Class Shape {

var numberofsides = 0

Func simpledescription (), String {

Return "A shape with \ (numberofsides) sides."

}

}

  Experiment//Exercises

  Add a constant property with Let, and the add another method that takes an argument.//Use to add a constant attribute, and then add a way with the parameter ;

An instance of a class is created by adding a () after the class name, accessing the instance method and using the point syntax for instance members.

var shape = shape ()

Shape.numberofsides = 7

var shapedescription = shape.simpledescription ()

In the preceding code example, the shape class lacks a very important thing: When an instance is created, it is not initialized. Use init to create an initialized instance.

Class Namedshape {

var numberofsides:int = 0

var name:string

Init (name:string) {

Self.name = Name

}

Func simpledescription (), String {

Return "A shape with \ (numberofsides) sides."

}

}

Notice how self in the above code distinguishes the name attribute from the name parameter in the initialization. When you create an instance of a class, the argument name is passed as if it were a function call. Each attribute member needs to be assigned a value, either in the declaration or in the initialization.

Use Deinit to define a method for Unregistering objects, in which you can perform some cleanup before the object is destroyed.

The subclass is written after the class name, plus the name of the parent class. In Swift, there is no requirement that subclasses must have the underlying root class, so at the right time, you can add or remove the parent class as needed.

The method of the subclass can override (override) The overridden method in the parent class, and if overridden (overriding) a method that does not have a tag override in the parent class, the compiler will give an error. The compiler also detects a method that is marked as override in a subclass, even if the method is not overloaded from the parent class.

Class Square:namedshape {

var sidelength:double

Init (sidelength:double, name:string) {

Self.sidelength = Sidelength

Super.init (Name:name)

Numberofsides = 4

}

Func area (), Double {

Return sidelength * sidelength

}

Override Func Simpledescription (), String {

Return "A square with sides of length \ (sidelength)."

}

}

Let test = Square (sidelength:5.2, Name: "My Test Square")

Test.area ()

Test.simpledescription ()

  Experiment//Exercises

 Make another subclass of Namedshape called Circle the takes a radius and a name as arguments to its initializer. Implement an area and a describe method on the Circle class.

/** Designs A subclass circle that inherits the Namedshape class, initializes its member variable radius and name, and then adds the area and describe methods to the class */

Another easy way to access member variables in a class is to use setters and getter.

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 Simpledescription (), String {

Return "an 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 above code example, the setter method of the member variable perimeter has an implied variable newvalue, which can also be added after set (), in which the variable is clearly defined.

Note There are three different steps for initializing in the Equilateraltriangle class:

    1. Sets the value of the member variable declared by the subclass;
    2. Invokes the initialization of the parent class;
    3. Modify the member variable values defined by the parent class, and other work done using getter or setter or instance methods.

/************* Follow-up content, please expect ***********/

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.