Swift learning "Swift Programming Journey---method (15)

Source: Internet
Author: User

Structs and enumerations can also define methods in swift, whereas in Objective-c, a class is the only type that can define a method.

  Instance method

An instance method is a method that belongs to a particular class, struct, or instance of an enumeration type that provides access to and modify instance properties, and the syntax of the instance method is exactly the same as the function. An instance method can implicitly access all other instance methods and properties of the type to which it belongs. An instance method can only be called by a specific instance of the class to which it belongs. An instance method cannot be called without being detached from an existing instance.

class Counter {   var0   func increment () {     count+ +   }   func IncrementBy (amount:int) {     + = amount   }   func reset ()     {0   

Call an instance method with dot syntax (dot syntax) just as you would call a property

  Local parameter name and external parameter name of the method

Swift defaults to only a local parameter name for the first parameter name of the method; The default gives both the second and subsequent parameter names the local parameter name and the external parameter name. This Convention is compatible with typical naming and calling conventions, similar to the way you write Objective-c. This Convention also allows the expression method to be called without qualifying the parameter name.

The following counter the other wording

class Counter {   var0   func incrementby (Amount:int, numberoftimes:int) {     + = Amount * numberoftimes   

The IncrementBy method has two parameters: Amount and Numberoftimes. By default, Swift only treats amount as a local name, but treats Numberoftimes as a local name and as an external name. This method is called below:

Let counter = counter () Counter.incrementby (53//
You do not have to define an external variable name for the first parameter value: because it can be clearly seen from the function name IncrementBy. The second parameter, however, is bounded by an external parameter name to clarify its role when the method is called. This default behavior can be an effective method of processing, similar to writing a pound sign (#) before the parameter numberoftimes:
func IncrementBy (Amount:int, #numberOfTimes: Int) {  + = Amount *

This default behavior makes the above code mean that the method defined in Swift uses the same syntax style as objective-c, and the method is invoked in the form of a natural expression.

  Modifying the external parameter name behavior of a method

You can add an explicit external name yourself or use a pound sign (#) as the prefix for the first parameter to take the local name as an external name. Conversely, if you do not want to provide an external name for the second and subsequent arguments of the method, you can override the default behavior by using an underscore (_) as the explicit external name for the parameter.

 Self property

Each instance of a type has an implicit property called "Self", which is equivalent to the instance itself. You can use this implicit self property to refer to the current instance in an instance method of an instance.

The increment method in the above example can also be written like this

 func increment () {   Self.count+ +   }

You don't have to use self frequently in your code. Swift assumes that you are referring to the properties or methods of the current instance. This assumption has been demonstrated in the above counter: count (not self.count) is used in the three instance methods in counter

When a parameter name of an instance method is the same as a property name of an instance, the precedence parameter name must be used in a more restrictive manner when referencing the property. You can then use the Self property to differentiate between the parameter name and the property name. In the following example, self eliminates ambiguity between the method parameter X and the instance attribute x:
structPoint {varx =0.0, y =0.0func ISTOTHERIGHTOFX (x:double)-Bool {returnself.x >x}} let Somepoint= Point (x:4.0Y:5.0) ifSOMEPOINT.ISTOTHERIGHTOFX (1.0) {println ("This-is-the right of the line where x = = 1.0") } //output "This dot is to the right of the line where x = = 1.0" (The point at X equals 1.0 to the left of this one)

If you do not use the self prefix, Swift thinks that X used two times refers to a function parameter with the name X

  To modify a value type in an instance method

Structs and enumerations are value types. In general, a property of a value type cannot be modified in its instance method. However, if you do need to modify the properties of a struct or enumeration in a specific method, you can choose the mutating keyword to decorate the instance method, and then the method can change its properties from within the method, and any changes it makes will remain in the original structure at the end of the method. The method can also assign an entirely new instance to its implied self property, and the new instance will replace the original instance after the method finishes. Place the keyword mutating before the Func keyword of the method
structPoint {varx =0.0, y =0.0mutating func Movebyx (deltax:double, y deltay:double) {x+=DeltaX y+=DeltaY}} varSomepoint = Point (x:1.0Y:1.0) Somepoint.movebyx (2.0Y:3.0) println ("the point was now at (\ (somepoint.x), \ (SOMEPOINT.Y))") //output "The point was now at (3.0, 4.0)"

Note: You cannot call a mutation method on a struct type constant, because a constant property cannot be changed, even if you want to change the variable property of a constant.

assigning self A value in the mutation method (assigning to self within a mutatingmethod)The mutating method can be assigned to an entirely new instance of the implicit property self. The above point example can be rewritten in the following way
struct Point {   var0.00.0   mutating func movebyx (deltax:double, y DeltaY: Double) {     = point (x:x + deltax, y:y + deltay)   

The mutation method of the enumeration can set self to a different member of the same enumeration type

enumTristateswitch { CaseOff, Low, high mutating func next () {SwitchSelf { Caseoff:self= Low Caselow:self= High Casehigh:self=Off}} } varOvenlight =tristateswitch.low ovenlight.next ()//ovenlight now equals. HighOvenlight.next ()//ovenlight now equals. Off

An enumeration of three-state switches is defined in the example above. Each time the next method is called, the switch loops before a different power state (Off,low,high).

Type MethodDeclare the type method of the class, precede the Func keyword of the method with the keyword class, declare the struct body and the type method of the enumeration, and precede the Func keyword of the method with the keyword static. Note: In Objective-c, you can only define type methods (Type-level methods) for objective-c classes. In Swift, you can define type methods for all classes, structs, and enumerations: Each type method is called explicitly by its supported type, with the same type method as the instance method, in point syntax.
class SomeClass {   class  func Sometypemethod () {     //  

In the method body (body) of a type method, self points to the type itself, not to an instance of the type. For structs and enumerations, this means that you can use self to disambiguate between static and static method parameters. In general, any unqualified method and property name will come from another type-level method and property in this class. A type method can invoke the name of another type method in this class without prefixing the method name with the type name. Similarly, struct and enum type methods can also access static properties directly from the name of a static property without requiring a type name prefix.

Swift learning "Swift Programming Journey---method (15)

Related Article

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.