Swift Learning Note 12

Source: Internet
Author: User
Tags access properties instance method

Method

A method is a function that is associated with a particular type. Classes, structs, enumerations can define instance methods and type methods. The type method is similar to the class method in OC.

Structs and enumerations can also be defined as a significant difference between Swift and C/oc, in which only classes can define methods.

Instance method

An instance method is a method that enumerates instances from a class instance or struct body instance. They provide functionality related to the instance, such as getting change properties or providing additional function functionality. The syntax and functions of an instance method are identical.

An instance method can implicitly access properties and methods of that type. Instance methods can only be invoked from instances of this type. Like what:

classCounter {var count=0func Increment () {count++} func IncrementBy (amount:int) {count+=Amount} func reset () {count=0}}let Counter=Counter ()//The initial counter value is 0counter.increment ()//The counter ' s value is now 1Counter.incrementby (5)//The counter ' s value is now 6Counter.reset ()//The counter ' s value is now 0

internal and external parameter names for methods

As mentioned earlier, the parameters of a function can have both an internal name and an external name, as is the case with the method. However, the default behavior and function of the internal and external names of the instance methods are different.

Like OC, the name of a method in Swift is usually picked up with a preposition such as with, for, by, and the first parameter name. For example, IncrementBy (_:) in the previous example, the preposition makes the method more readable when it is called, just like a coherent sentence. So swift makes this method more convenient by giving the method parameters a different default behavior than the function: Swift gives the first parameter name of the method the internal parameter name, and both the internal and external parameter names are provided for the second and subsequent parameter names.

Still above a counter as an example, assuming that its instance method IncrementBy requires two parameters:

class Counter {    0    func incrementby (Amount:int, numberoftimes:int) {        + = Amount *  Numberoftimes    }}

By default, Swift considers the first parameter name amount only as an internal parameter name, and Numberoftimes as both an internal and an external variable name. Therefore, when invoking this instance method:

Let counter = counter () Counter.incrementby (53)//  counter value is now

There is no need to define an external parameter name for the first parameter of the method, because its meaning can be expressed explicitly by means of the method name IncrementBy, but the parameters in the back require the external parameter names to make the semantics very clear when the method is called. This default is handled as if you had added the (#) symbol to each of the second and subsequent parameter names at the time of the method definition.

Of course, if you want to change this default behavior, specify an external parameter name for the first parameter, or you can specify it in the usual way, if you don't want to add the default external parameter name to the second and later arguments, you can precede the parameter name with an underscore (_) as the name of the external argument.

Self property

Each instance object has an implicit property of self, which points to the instance object itself. In actual development, it is not necessary to write self frequently, within instance methods, if you do not explicitly indicate self, each time you use a property or method that you have always, Swift assumes that you are using the property or method of the current object. One of the main exceptions to this principle is that when the parameter name of the method and the property name of the instance object are the same, the method's argument name has a higher priority, and if you need to use the properties of the instance object, you need to use self.

To change a value type from within an instance method

Structs and enumerations are value types, and by default, a property of a value type cannot be changed from within its instance method.

However, if you want to change the property value of a struct or enumeration from inside a particular method, you can choose to change the behavior of that method. The method can then change its properties from within, and any changes it produces will be written to the original structure at the end of the method. The method can also give an entirely new instance object to its implicit property, and when the method ends, the new instance replaces the existing one.

Implement the above behavior by adding the keyword mutating before the func:

structPoint {var x=0.0, y =0.0mutating func Movebyx (deltax:double, y deltay:double) {x+=DeltaX y+=DeltaY}} var somepoint= Point (x:1.0Y:1.0) Somepoint.movebyx (2.0Y:3.0) println ("the point was now at (\ (somepoint.x), \ (SOMEPOINT.Y))")//Prints "The point was now at (3.0, 4.0)"

In the example above, a mutating method Movebyx is defined to move the point object at a distance, which is directly manipulated on the current point object instead of returning a new point object.

Note that if you assign a value type instance object to a constant, you cannot invoke its mutating method, because once assigned to a constant, all its properties cannot be changed, even if the property is a variable property.

Assigning self to self from within the mutating method

The mutating method can assign an entirely new object to the implicit attribute self, such as the example above can be rewritten as:

struct Point {    0.00.0    mutating func movebyx (deltax:double, y deltay:double) {        
    = Point (x:x + deltax, y:y + DeltaY)    }}

This method returns a new Point object instance, but when the method is complete, the result is exactly the same as the previous example.

The mutating method of an enumeration type can set the implicit property self to another distinct member of this enumeration:

enumTristateswitch { CaseOff, Low, high mutating func next () {SwitchSelf { Caseoff:self= Low Caselow:self= High Casehigh:self=Off}}} var ovenlight=TriStateSwitch.LowovenLight.next ()//Ovenlight is now equal to. HighOvenlight.next ()//Ovenlight is now equal to. Off

Type method

As mentioned earlier, an instance method is a method that is called on an instance object. A type method, however, refers to a method that is called from the type itself. Declare a type method by adding the keyword static before the func. Classes can also use the class keyword to allow subclasses to overload the implementation of the method by the parent class.

In OC, type methods can only be declared on a class, whereas in Swift, type methods are declared on classes, structs, enumerations. Various types of methods are shown to indicate the types that it supports.

class SomeClass {    class  func Sometypemethod () {        //  type method Implementation goeshere    }}someclass.sometypemethod ()

Inside a type method, the implicit attribute self points to the type itself, not to its instance object. For structs and enumerations, this means that a distinction can be made when the Type property name and the method parameter name are the same.

Typically, undefined methods and property names that occur inside a type method will point to the Type property and type method of the kind, and do not need to prefix the type name with the property and method name.

Subscript

Subscript is an easy way to get the elements in a collection, list, or queue, and the subscript can fetch and store values through an indexed sequence (index) without the need for additional fetching and setting methods.

Classes, structs, and enumerations can define subscripts, you can define multiple subscripts for a type, subscript is not limited to one dimension, and you can define subscripts with multiple parameters.

Under the banner law

The following slogan enables you to query an instance object by writing a bracket that contains one or more values after the instance name. Syntax and instance method syntax and computational property syntax are very similar. The subscript is defined by the Subscript keyword, and then one or more input parameters and return types are specified as an instance method. Unlike an instance method, the subscript can be read-only and alive and written. This behavior is similar to the getter and setter for the computed properties:

Subscript (index:int), Int {    get  {        //  return an appropriate Subscript valuehere    }    set(newvalue) {        //  perform A suitable setting actionhere    }}

This setter is similar to the computed property, if you specify a new value parameter name, then the name, if not specified, is provided by default to NewValue.

If the subscript is read-only, the setter is removed, similar to the computed attribute, and only the getter can omit the Get keyword in shorthand form.

struct timestable {Let    multiplier:int    , Int {        return multiplier * index     3) println ("six times three is \ (Threetimestable[6])" )//  prints "six times three is"

The subscript can accept any number of arguments of any type or return any type of return value. The subscript can use variable arguments and variable arguments, but you cannot use the In-out parameter, nor can you provide a default value for the parameter.

Classes and structs can provide many of the following table implementations as needed. Which method will be used depends on the type of the parameter in square brackets when using the subscript, which is also called the subscript overload.

The subscript usually takes a parameter, and of course it can be defined as accepting multiple parameters:

structMatrix {Let rows:int, columns:int var grid: [Double] Init (rows:int, columns:int) {self.rows =rows Self.columns=Columns Grid= Array (count:rows * columns, Repeatedvalue:0.0)} func indexisvalidforrow (Row:int, Column:int)-Bool {returnRow >=0&& row < rows && column >=0&& Column <columns} subscript (Row:int, Column:int)-Double {Get{assert (Indexisvalidforrow (row, column:column),"Index out of range")            returngrid[(Row * columns) +Column]} Set{assert (Indexisvalidforrow (row, column:column),"Index out of range") grid[(Row* columns) + column] =NewValue}}}

var matrix = matrix (Rows:2, Columns:2)

Matrix[0, 1] = 1.5

matrix[1, 0] = 3.2

Inherited

A class can inherit a method, property, or other attribute from another class, the inheriting class is called a subclass, and the inherited class is called a superclass. Inheritance is a major feature of classes that differ from other types.

Classes can access the properties, methods, and subscripts of its superclass, or they can provide their own overloaded versions of these properties, methods, and subscripts to alter their behavior. Class can also add property observers to inherited properties, whether this property is a stored or computed property in a superclass.

Any class that does not inherit from another class is called a base class. Classes in Swift are not uniformly inherited from a global base class, and if you create a class that does not inherit from any class, it is the base class.

class Vehicle {    0.0    // This is a read-only computed property        return"  traveling at \ (currentspeed) miles per hour"    }    func makenoise () {         // do nothing-an arbitrary vehicle doesn ' t necessarily make a noise    }}

This defines a base class that does not inherit from any class, and one of its instance methods is not implemented, which is left to the subclass for concrete implementation.

A subclass is defined by a colon after the class name, followed by the name of the superclass:

class bicycle:vehicle {    false}

Subclasses inherit the properties of the superclass by default, such as the bicycle class automatically has the Currentspeed attribute and the Makenoise method. Of course, subclasses can also define their own properties and methods, subclasses can be inherited again, and subclasses will sequentially get the attributes of those superclass on the inheritance chain.

Overload

Subclasses can provide their own implementation versions for inherited instance methods, type methods, instance properties, type properties, and subscripts, otherwise they are implemented in a way that inherits from the superclass. This is called overloading.

The overloaded implementation is preceded by the keyword override to indicate that an attribute is overloaded, which means that you intentionally reload an attribute instead of accidentally using the same name or definition. In fact, any overloads without the Override keyword will trigger an error at compile time. The override keyword also causes Swift to check that the overloads match the attributes in the superclass to ensure that the overloads are defined correctly.

Sometimes, when subclasses overload a superclass, you may need to access the superclass's implementation of the class, which accesses the properties, methods, and subscript implementations of the superclass through the super prefix.

The overloaded method is to add the override keyword before the func of the method.

Any inherited property can be overloaded, you can provide a custom getter, or you can provide a custom setter when needed, whether the property is defined as a stored property or a computed property in a superclass. It is impossible to know whether a property in a superclass is a stored or computed subclass, and it knows only the name and type of the property. You must also specify the name and type of the overloaded property so that swift checks if the overload is correct. You can overload a read-only property in a subclass by providing a getter and setter to read-write properties, and then you cannot overload a read-only property with a readonly one.

Note: If you provide a setter when you reload, you must also provide a getter as part of the overload.

class car:vehicle {    1    override  var description:string {        return " In gear \ (gear) "     }}

You can add an observer to an inherited property through property overloading, regardless of how the property was originally implemented and defined, and you can be notified when it changes.

Note: You cannot add observers to inherited constant store properties or read-only computed properties that cannot be changed, so it is not appropriate to provide willset and didset when overloaded. Also, you cannot overload both the setter of a property and its observer, because if you overload the setter, you can implement the observer's purpose directly inside the setter.

class Automaticcar:car {    override  var currentspeed:double {        Didset {            10.0 1         }    =35.0println ("Automaticcar: \ ( automatic.description)//  automaticcar:traveling at 35.0 miles per hour In Gear 4

Prevent overloading

You can prevent methods, attributes, or subscripts from being overloaded by marking the final version by adding the final keyword to their keywords, such as: Final Var, final func, Final class func, final subscript, and so on.

Any attempt to reload an attribute that has been marked as final will trigger a compile-time error.

You can also include the final keyword in front of the Class keyword class to mark the entire class as the final version, and any attempt to inherit the final class will trigger a compile-time error.

Swift Learning Note 12

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.