Swift is a new language developed by Apple, which certainly has many object-oriented features, and now begins to introduce the syntax of classes and objects in Swift.
Objects and classes
To create a class with "Class" plus a class name, the attribute declaration and declaration constant or variable are the same, except that it is declared within the class. Methods and function declarations are the same:
Class Shape { var numberofsides = 0 func simpledescription ()-String { return ' A Shape with \ (numberofsid ES) sides. " }}
It is also very simple to create a class object, notice that there is no use of the new keyword, and that the properties and methods of the class object are accessed through the.
var shape = shape () shape.numberofsides = 7var shapedescription = shape.simpledescription ()
In the declaration of a class, there is usually initialization method init,
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 this uses self to refer to the current class object, which distinguishes between the property name and the parameter name of the incoming Init method.
Each property needs to be assigned, either when it is declared or in the initialization method.
Use the Deinit method to create a destructor to do some cleanup before the class object is freed.
The inheritance syntax for a class is also simple, with a colon plus the parent class name. There is no contract that the subclass must inherit from which root class, so inheritance is not required. Subclasses override the parent class method with the override identity. If the subclass has a method with the same name as the parent class without override, the compiler will error. The compiler also probes for methods that identify the override but do not have the same name in 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 () /c16>
Simple properties can be saved directly, and properties can have accessors:
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 }} ov Erride func simpledescription (), String {return "an equilateral triangle with sides of length \ (sidelength)." }}var triangle = Equilateraltriangle (sidelength:3.1, Name: "A triangle") println (Triangle.perimeter) Triangle.perimeter = 9.9println (triangle.sidelength)
In the setter, the name of the new value is implicitly newvalue, or it can be displayed to indicate a different name after set.
If your property does not need to be evaluated, but you still need to write some logic before or after the setpoint, you can use Willset and didset, for example, the following class ensures that its triangle's side length and square side length are always equal:
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") println (triangleAndSquare.square.sideLength) println ( triangleAndSquare.triangle.sideLength) triangleandsquare.square = Square (sidelength:50, name: "Larger square") println (triangleAndSquare.triangle.sideLength)
There is a very important difference between the methods of a class and the general function. The parameter name of the general function is only used inside the function, but the parameter name of the class method is also used when you invoke the method (except for the first argument). By default, when you call a method, the method has the same parameter name as its interior. You can specify a different name, which will be used inside 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 processing can omit variables, you can add a question mark before operations such as properties, methods, subscript. If the value before the question mark is nil, all expressions after the question mark are ignored, and the value of the entire expression is nil. Otherwise, the omitted value is expanded, and all expressions after the question mark are based on the expandable ellipsis value. However, the value of the entire expression is an ellipsis.
Let Optionalsquare:square? = Square (sidelength:2.5, name: "Optional Square") let Sidelength = Optionalsquare?. Sidelength
Enumeration types and struct bodies
Use enum to create an enumeration type variable. Like classes and other types, enumeration types can have methods that correspond to them:
Enum Rank:int {case aces = 1 Case -Three, four, Five, Six, Seven, Eight, Nine, Ten case Jack, Queen, King func simpledescription (), String { switch self { case . Ace:return "Ace" case . Jack:return "Jack" case . Queen:return "Queen" Case . King:return "King" Default: Return String (self.rawvalue)}}}let ace = rank.ace//enum Value
Let Acerawvalue = Ace.rawvalue//1
In the above example, the original type (Raw-type) of the enum type variable rank is of type int, so only the first value is assigned, and the remaining value is automatically given at one time. You can also set the original type of the enumeration variable to a string or a floating-point number, and use RawValue to get the original value of the enumeration variable. With Init? (rawValue:) initializer creates an instance of an enumeration type from an original value.
if 3 ) { = convertedrank.simpledescription ()}
The member value of an enumeration type is the actual value, not another way of writing the original (raw value), in fact, there is no real original value in the so-called true meaning, and you do not need to assign the original value to each enum type member
enumSuit { CaseSpades, Hearts, Diamonds, Clubs func simpledescription ()-String {SwitchSelf { Case . Spades:return "Spades" Case . Hearts:return "Hearts" Case . Diamonds:return "Diamonds" Case . Clubs:return "Clubs"}}}let Hearts=Suit.heartslet heartsdescription= Hearts.simpledescription ()
Note that there are two ways to reference the value of a member of an enumeration type instance: When you copy it as a value to a constant hearts, The suit.hearts is indicated by the display, because the constant does not implicitly indicate the type, and within switch, the member value of the enumeration type is abbreviated. Hearts is quoted because the type of self is already known to be the appropriate type. This shorthand can be used when any variable type is known and appropriate.
Structural body
struct keywords are used to create structs, and structs support the behavior of many classes, including methods and initializers. The biggest difference between a struct and a class is that when passed in the code, the struct is always copied, and the class only passes the reference.
struct Card { var rank:rank var suit:suit - String { return' The \ (Rank.simpledescription ()) of \ (Suit.simpledescription ())"//directly refers to an expression or variable in a string == threeofspades.simpledescription ()
An instance of an enumeration type member can have a value associated with an instance (associated value), and different instances of an enumeration type member can have different values associated with them, which are provided when the instance is created.
The associated value (associated value) is different from the original value (Raw values): The original value of the member of the enumeration type is the same for all instances, and the original value needs to be given when the enumeration type is defined.
Give me a chestnut. When data is requested for sunrise and sunset times on a server, the return of the server is divided into two situations: returning the appropriate time or returning an error
enumServerresponse { CaseResult (String, String) CaseError (String)} Let success= Serverresponse.result ("10:00am-6:00pm","8:09 pm") Let failure= Serverresponse.error ("Out of cheese.") SwitchSuccess { CaseLet . Result (Sunrise, Sunset): Let Serverresponse="Sunrise are at \ (Sunrise) and sunset are at \ (sunset)." CaseLet . Error (Error): Let Serverresponse="Failure ... \ (error)"}
Note how sunrise and sunset are taken out of the serverresponse as part of the case that matches the switch.
Swift Learning Note two