Apple new programming language Swift language Advanced (vii)--enumeration, structure, class

Source: Internet
Author: User

http://blog.csdn.net/goohong/article/details/31769677

In the swift language, types that have class characteristics are three, that is, enum types, struct types (including primitive types, the basic types are actually exceptions to struct types), and classes. Where the enumeration type, struct type is a value type, and the class belongs to the reference type. There are three types that can add attributes, methods, subscript methods, extend functionality using extensions, use protocols, and more.

First, enumerate

An enumeration defines a public type that contains a set of related values. An enumeration is a class-like type in swift, with many characteristics of traditional classes, such as computed properties, instance methods, and the ability to extend or protocol enhancements.

1.1 Enumeration definitions

The definition syntax for the Swift language enumeration type is as follows:

Enum CompassPoint {

Case North

Case South

Case East

Case West

}

The enumeration syntax is identified by a keyword enum, which is followed by an enum-type name, and the enumeration definition is placed in a pair of curly braces.

The value defined in the enumeration is called an enumeration member value, and the case keyword is used to indicate a new enumeration member value.

Unlike the enumeration types in the C and Objective-c languages, there is no need to assign a default integer value to an enumeration member in Swift.

If you provide a value for an enumeration member, the value can be a string, a character, or an arbitrary integer or floating-point number.

Enumeration member values can be defined in one row and separated by commas.

Enum Planet {

Case Mercury,venus,earth,mars,jupiter,saturn,uranus,neptune

}

Each newly defined enumeration belongs to a new, independent type.

1.2 Use of enumerations

You can assign a value of an enumeration type to a constant or variable, such as:

var directiontohead =compasspoint.west

The variable directiontohead defined above can be inferred as an enumeration variable of type CompassPoint, so you can set the variable to another value of type compasspoint, such as:

Directiontohead =. East//enum type omitted

Enumerations can also be used in a switch statement to match a separate enumeration value:

Directiontohead =. South

Switch Directiontohead {

Case. North:

println ("Lots of Planets has a North")

Case. South:

println ("Watch Out for Penguins")

Case. East:

println ("Where The Sun Rises")

Case. West:

println ("Where The Skies is Blue")

}

1.3 Assigning related values to enumeration members

In Swift, you can specify an arbitrary type of correlation value for each enumeration member, and the type of related values specified for each enumeration member may be different.

Enum Barcode {

Case UPCA (Int,int,int)

Case QRCode (String)

}

This example defines an enumeration type of type barcode, defines two enumeration values UPCA and QRCode, and can assign a correlation value for the enumeration value UPCA to a multivariate group type, assigning QRCode a correlation value for the string type, which does not specify any type of value for the enumeration value itself.

You can use the enumeration defined above to assign a value to a constant or variable, such as:

var productbarcode =barcode.upca (8,85909_51226,3)

The example assigns a BARCODE.UPCA enumeration value to the variable productbarcode, assigning the value of the associated multivariate group type to (8,85909_51226,3).

The variable productbarcode can then be set to an additional enumeration value with a string type-related value:

Productbarcode =. QRCode ("Abcdefghijklmnop")

You can also use the enumeration in a switch statement and draw a value of its associated type by binding a constant or variable:

Switch Productbarcode {

Case. UPCA (let Numbersystem,let identifier,let check):

println ("Upc-a with value of\ (Numbersystem), \ (identifier), \ (check).")

Case. QRCode (Let ProductCode):

println ("QR Code with value of\ (ProductCode).")

}

If all the associated values of an enumeration member are drawn as constants, or if all related values are drawn as variables, the syntax can be abbreviated as follows:

Switch Productbarcode {

Case Let. UPCA (Numbersystem,identifier,check):

println ("Upc-a with value of\ (Numbersystem), \ (identifier), \ (check).")

Case Let. QRCode (ProductCode):

println ("QR Code with value of\ (ProductCode).")

}

1.4 Assigning the original value to an enumeration

In addition to assigning related values to enumeration members, you can pre-assign a primitive value of the same type to each enumeration member. This is similar to the C language assigning an integer value to an enumeration member, but the type of the original value defined by Swift can be a string, a character, or any integer or floating-point type, such as:

Enum Asciicontrolcharacter:character {

case tab = "\ t"

Case linefeed = "\ n"

Case Carriagereturn = "\ r"

}

In this example, an enumeration type Asciicontrolcharacter with three enumeration members is defined, and the original type is specified as a character type, and each enumeration member is assigned a default original value of the character type.

Similar to the C language specifying values for enumeration members, Swift requires that the original value assigned for each enumeration member of the enumeration must be unique within the enumeration declaration. When using the original value of an integer type, the other original value of the enumeration member, if not specified, can automatically add 1 on the basis of the first enumeration member definition value, as follows:

Enum Planet:int {

Case Mercury =1,venus,earth,mars,jupiter,saturn,uranus,neptune

}

The original value defined for an enumeration member differs from the correlation value assigned to the enumeration member, and the original value of the enumeration member is assigned when the enumeration is first defined, while the associated value of the enumeration member is specified when the enumeration is defined, but its value is set when a constant or variable is created with the enumeration type.

In Swift, you can use the Toraw method of an enumeration member to get the original value of an enumeration member:

Let Earthsorder = Planet.Earth.toRaw ()

Conversely, you can also use the Fromraw method of an enumeration type to return an enumeration member that corresponds to the original value, which returns an option because its value may or may not exist. as shown below.

Let Possibleplanet =planet.fromraw (9)

Returns an enumeration member that corresponds to the original value 9 of the enumeration planet. Is the return a planet? Option type, in which case the value does not exist and returns a nil.

Two structures and classes

2.1 Comparison of the two

In Swift, the structure and class functions are almost identical, and both have the same functionality as the following:

1) attributes can be defined to store values;

2) methods can be defined to provide functions;

3) You can define a scripting method to use the script syntax to access their values;

4) Ability to define initialization methods to set their initial state;

5) can be extended to increase the previously not implemented functions;

6) be able to comply with the relevant protocol to provide the standard function of determining type.

Class differs from structure in the following ways:

1) classes can inherit, a class can inherit its superclass, and the structure can not inherit;

2) class allows you to check and interpret the type of a class instance at run time;

3) classes can have destructors that allow instances of the class to release any resources that it allocates;

4) A reference count allows a class instance to have multiple references.

5) structs are always copied in the code, rather than using reference counts.

2.2 Definition and instantiation of classes and structs

Classes and structs are defined with similar syntax, and classes are indicated using the class keyword, which is indicated by the struct keyword.

struct Resolution {

var width =0

var height =0

}

Class Videomode {

var resolution =resolution ()

var interlaced =false

var framerate =0.0

var name:string?

}

Each newly defined class or struct defines a new type.

The above example defines a new struct type called resolution, which contains and defines the properties of two variable types. It also defines a new class, called Videomode, that defines and contains properties of four variable types whose first property, resolution, is initialized with an instance of the struct resolution that was just defined.

Properties of variables or constant types defined in classes and structs are initialized and assigned as normal variables and constants, and the type of the property can be inferred based on the initial value provided for it.

The syntax for creating instances for classes and structs is the same:

Let Someresolution =resolution ()

Let Somevideomode =videomode ()

This example takes the simplest syntactic form of structure and class initialization (the structure and class type name face are followed by a pair of parentheses). The initialization syntax creates a new individual instance of the struct and class, assigns a value to two constants, and the properties of two instances are also initialized to their default values in the initialization method.

In swift, all struct types automatically produce a parameter initialization method that can be used to initialize and create new instances of the struct and its member properties, and the initial values of the properties of the newly created instance use the values passed in by the parameters of the initialization method, such as:

Let VGA =resolution (width:640,height:480).

The class does not provide a corresponding default parameter initialization method.

In Swift, like the scripting language, you can use point syntax to access the properties of a struct or class instance and its sub-properties, that is, to read and set its value:

Read the value of the property:

println ("The width of someresolution is\ (someresolution.width)")

println ("The width of Somevideomode is\ (someVideoMode.resolution.width)")

Set the value of a property:

SomeVideoMode.resolution.width = 1280

2.3 Types of structs, classes, and enumerations

In Swift, structs and enumerations are the same value types as other basic types (integer, floating-point type, Boolean type, string, array, and dictionary, which are actually implemented as struct types). This means that when they are assigned to a variable or constant or when it is passed as a parameter to a function, their instances and all of the attributes they contain are copied one by one as a value type.

In Swift, in order to provide performance, the copy uses a mechanism of delayed copying, which is copied only when it is actually used.

Let HD = Resolution (width:1920, height:1080)

var cinema =hd

In this example, because resolution is a struct type, constant HD and variable cinema are different instances of the resolution struct type because copy behavior occurs when assigning a value to a variable cinema.

Unlike structs and enumerations, a class's type belongs to a reference type. When an instance of a reference type is assigned to a variable or constant or when it is passed as a parameter to a function, no copy occurs.

Let Teneighty =videomode ()

Teneighty.framerate = 25.0

Let Alsoteneighty =teneighty

Alsoteneighty.framerate =30.0

Since Videomode belongs to a class, now the two constants Teneighty and Alsoteneighty refer to the same Videomode instance, just the different names for the same instance, so the property values for both constants framerate are now equal to 30.0.

Note that the above teneighty and Alsoteneighty are declared as two constants, not variables, because Teneighty and alsoteneighty itself store only the reference value of the Videomode instance, not the Videomode instance itself , so you change the properties of the referenced class instance by their changes to the properties of the class instance itself, not the reference itself.

Because the class is a reference type, as shown in the example above, multiple variables or constants may refer to the same instance of a class. To determine whether two constants or variables refer to the same instance of a class, Swift provides two reference comparison operators: ' = = = ' and '!== '. You can use these two operators to check whether two constants or variables refer to the same instance:

If Teneighty ===alsoteneighty {

println ("Teneighty and Alsoteneighty refer to the same Resolution instance.")

}

In Swift, a constant or variable refers to an instance of a class, similar to a pointer in the C language, but in Swift, the reference is not directed to an address in memory, so it is not necessary to use a similar pointer symbol ' * ' in C to represent a reference or pointer.

All rights reserved, please reprint is clearly marked link and source, thank you!

Copyright NOTICE: This article for Bo Master original article, without Bo Master permission not reproduced.

Apple new programming language Swift language Advanced (vii)--enumeration, structure, class

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.