A detailed approach to the Swift tutorials _swift

Source: Internet
Author: User
Tags instance method types of functions

Method is a function that is associated with a specific type. Class, struct, enumeration all can define instance methods, encapsulate specific tasks and functions to handle an instance of a given type. A class, struct, enum type can also define a method, the associated type itself. The type method is similar to the Objective–c class method.

Structs and enumerations can define methods Swift is a significant difference from C and objective–c. In Objective–c, a class is a unique type that can define a method. At Swift, you can choose whether you want to define a class, structure, or enumeration, as well as the flexibility to create the type of method you define.

1. Example method

An instance method is a function of a particular class, struct, or enumeration instance. They support the functionality of these instances, either by providing methods to access and modify instance properties, or by providing functionality and instance purposes. Instance methods have exactly the same syntax functions, such as functional descriptions
Open and close parentheses within the type you belong to write an instance method. An instance method has implicit access to all other instance methods and properties of that type. An instance method can only be invoked on a particular instance of the class to which it belongs, and it cannot access a nonexistent instance.
Here, a simple counter class is defined that can be used to count an example of how many times an action occurs:

Copy Code code as follows:

Class Counter {
var count = 0
Func increment () {
count++
}
Func IncrementBy (amount:int) {
Count + = Amount
}
Func Reset () {
Count = 0
}
}

The counter class can define three instance methods:
Increment increment counter 1.
IncrementBy (amount:int) increments the counter by the specified integer amount.
Resets the value of the counter to zero.
The Count class also declares a variable attribute, statistics, and tracking the current counter value.
You call an instance method with a property of the same point syntax

Copy Code code as follows:

Let counter = counter ()
The initial counter value is 0
Counter.increment ()
The counter ' s value is now 1
Counter.incrementby (5)
The counter ' s value is now 6
Counter.reset ()
The counter ' s value is now 0

Methods for local and external parameter names

Function arguments can have a local name (used in a function body) and an external name (used when calling a function), and the external parameter name. The same is true for method arguments, because methods are related to type functions. However, the default behavior of local and external names is different functions and methods.

method is very similar to Objective–c's peers in Swift. In Objective–c, the name of a method in Swift is usually referred to as the first parameter of the method using preposition, or, as in the IncrementBy method, from the previous example of the Counter class. The use of a method that can be interpreted as a judgment is called preposition. Swift makes this method of establishing naming conventions easy to write by using a different default method.

Specifically, Swift gives the first parameter name method The default local parameter name and gives the second and subsequent parameter names default local and external parameter names. This Convention can be invoked in a familiar objective–c and makes the expression method call without having to conform to your parameter name.

Consider this alternative version of the counter class, which defines a more complex form of the IncrementBy method:

Copy Code code as follows:

Class Counter {
var count:int = 0
Func IncrementBy (Amount:int, Numberoftimes:int) {
Count + = Amount * Numberoftimes
}
}

This has two Parameters-amount and Numberoftimes IncrementBy methods. By default, Swift treats amount as a local name, but Numberoftimes as a local and external name. The method you call is as follows:

Copy Code code as follows:

Let counter = counter ()
Counter.incrementby (5, Numberoftimes:3)
Counter value is now 15

You do not need to define an external parameter name as the first parameter value, because it is an explicit function name IncrementBy. However, the second parameter is qualified by the external parameter name.
This default behavior is valid for external methods, if you have numberoftimes parameters before writing a hash symbol (#):

Copy Code code as follows:

Func IncrementBy (Amount:int, #numberOfTimes: Int) {
Count + = Amount * Numberoftimes
}

The default behavior described above is written in Swift with the same method definition, syntax similar to Objective–c, and can be invoked more conveniently.

To modify an external parameter name behavior method

Sometimes it is useful to provide the parameter name of the first parameter of an external method, even if this is not the default behavior. You can add an explicit external name yourself, or you can use the local name as the name of the first parameter in the name of a hash prefix.
Conversely, if you do not want to provide a second method for the external name or subsequent parameters, override the default behavior by using the underscore character (_) as an explicit argument to the external parameter name.

Self property

Each instance of a type has a so-called implicit self attribute, which is exactly equivalent to the instance itself. You can use this implicit self property to refer to its own instance method in the current instance.

In the example above, the increment method can also be written like this:

Copy Code code as follows:

Func increment () {
self.count++
}

In practice, you don't need to write self, which in your code will be very frequent. If you do not explicitly write self,swift assume that you are referring to the properties or methods of the current instance, whenever you use a known property or method name in a method. This assumption is proof that the counters of the three instance methods inside are using count (rather than self.count).
The main exception occurs when the parameter name of an instance method has the same name as the property of the instance. In this case, the parameter name takes precedence, and there is a need to refer to the attribute more qualified way. You can use the implicit attribute's parameter name and property name to differentiate.
If a method parameter is called X, and an instance property is also called X, you can automatically disambiguate two x in Swift without confusing it.

Copy Code code as follows:

struct Point {
var x = 0.0, y = 0.0
Func ISTOTHERIGHTOFX (x:double)-> Bool {
return self.x > x
}
}
Let Somepoint = Point (x:4.0, y:5.0)
If SOMEPOINT.ISTOTHERIGHTOFX (1.0) {
println ("This point is to the right of the" where x = = 1.0)
}
Prints "This point is to the right of the" where x = = 1.0 "

If there is no self prefix, Swift will assume that the two uses of X are called method parameters of X

To modify an instance method of a value type

Structure and enumeration value types. By default, a property of a value type cannot modify its instance method
However, if you need to modify the property structure or enumerate in a particular way, you can select the method of change behavior. But any change will cause it to be written at the end of the method to return to the original structure. When the method ends, you can also assign an entirely new instance to its implied self attribute, and the new instance replaces the existing one.
You can select this behavior before inserting a Variant keyword into the function keyword method:

Copy Code code as follows:

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

The point structure defines a mutation Movebyx method that moves a point instance through a quantity. Instead of returning a new starting point, this method actually modifies the call point on it. The mutation contains the definition added to it to enable it to modify its properties.
Note that you cannot call a constant of a Variant method struct type, because its properties cannot be changed, even if they are mutable attributes, such as a property description stored in a fixed structure instance:

Copy Code code as follows:

Let FixedPoint = Point (x:3.0, y:3.0)
Fixedpoint.movebyx (2.0, y:3.0)
This'll is an error

The self mutation method in distribution
The mutation method can assign a completely new instance to the implied self attribute. Examples of the points shown above can also be written in the following way instead:

Copy Code code as follows:

struct Point {
var x = 0.0, y = 0.0
mutating func Movebyx (deltax:double, y deltay:double) {
Self = point (x:x + deltax, y:y + deltay)
}
}

This version of the mutation Movebyx method creates an entirely new structure whose x and Y values are set to the target location. The result of calling this method is exactly the same as the previous version

Variable method enumeration You can set the self argument to be a different member from the same enumeration

Copy Code code as follows:

Enum Tristateswitch {
Case out, low, high
Mutating func Next () {
Switch Self {
Case OFF:
Self = Low
Case Low:
Self = high
Case High:
Self = Off
}
}
}
var ovenlight = Tristateswitch.low
Ovenlight.next ()
Ovenlight is now equal to. High
Ovenlight.next ()
Ovenlight is now equal to. Off

This example defines a three-state switch enumeration. Switching cycles between three different power states (off, low, high)

2. Type method

As noted above, the method of an instance method requires an instance of a particular type. You can also define a method of the type itself, which is called the type method, and the type method that you display directly begins with class func in the struct body, and for enumerations and structs, the type method begins with a static func.
Please note;
In Objective–c, you can define Type-level methods only for objective–c classes. In Swift, you can define Type-level methods, structs, and enumerations for all classes. The display of each method is limited to the type that it supports.
The type method calls the dot syntax, just like an instance method. However, you are calling a method of the type, not an instance of that type. Here's how you call a class to call a SomeClass type of method:

Copy Code code as follows:

Class SomeClass {
Class Func Sometypemethod () {
Type method implementation goes here
}
}
Someclass.sometypemethod ()

In the body of a type method, the implied self property refers to the type itself, not to an instance of the type. For structs and enumerations, this means that you can use self-service static properties and static method parameters to disambiguate, just as you do the arguments of instance properties and instance methods.

More generally, you use any unqualified method and attribute names in a method body of a type to refer to other Type-level methods and properties. One method can call the method of another class and the names of other methods, without having to prefix the type name. Similarly, methods of structure and enumeration types can use the name of a static property and have no type name prefix to access static properties.

The following example defines a structure called Leveltracker that tracks the progress of a player through different levels or stages of the game. This is a single player game, but can store information for multiple players on a single device.

All the level of the game (except for the first level) when the game is played for the time being. Each time the player completes a level, the level unlocks all players on the device. The Leveltracker structure uses static properties and methods to track which levels of the game have been unlocked. It also tracks the current level of individual players

Copy Code code as follows:

struct Leveltracker {
static var highestunlockedlevel = 1
static func Unlocklevel (Level:int) {
If level > Highestunlockedlevel {
Highestunlockedlevel = level
}
}
static func levelisunlocked (level:int)-> Bool {
return level <= Highestunlockedlevel
}
var currentlevel = 1
mutating func advancetolevel (level:int)-> Bool {
If leveltracker.levelisunlocked (level) {
CurrentLevel = level
return True
} else {
return False
}
}
}

The Leveltracker structure tracks the highest level of unlock for any player. This value is stored in a static property named Highestunlockedlevel.

Leveltracker also defines two types of functions and highestunlockedlevel, first of which is called the Unlocklevel function, whenever a new horizontal unlock is used to update the Highestunlockedlevel, The second is the levelisunlocked function, which returns ture if a specific number of levels has been unlocked. Note that these types of methods can access highestunlockedlevel static properties but you need to write it as Leveltracker.highestunlockedlevel.

In addition to its static properties and types of methods, Leveltracker tracks the progress of each player through the game. It uses what is called the CurrentLevel instance property to track the player level.
To help manage the Urrentlevel property, Advancetolevel Leveltracker defines an instance method. This method is used to check whether a new level has been unlocked before CurrentLevel is updated. The Advancetolevel method returns a Boolean value indicating whether it can set the CurrentLevel.
The Leveltracker structure uses the Player class, as shown below, to track and update individual player progress:

Copy Code code as follows:

Class Player {
var tracker = Leveltracker ()
Let playername:string
Func Completedlevel (level:int) {
Leveltracker.unlocklevel (level + 1)
Tracker.advancetolevel (level + 1)
}
Init (name:string) {
PlayerName = Name
}
}

The player class creates a new instance of Leveltracker to track the player's progress. It also provides a method called Completedlevel, which unlocks a new level and progress and moves the player to the next level whenever the player reaches a specific level. (The Boolean value returned by Advancetolevel will be ignored because the leveltracker.unlocklevel is known to be called.) )
You can create a new player instance of players to see what happens when a player completes a level:

Copy Code code as follows:

var player = player (name: "Argyrios")
Player.completedlevel (1)
println ("Highest unlocked level are now" (Leveltracker.highestunlockedlevel))
Prints "highest unlocked level are now 2"

If you create a second player and you want to try to move to a level that has not been unlocked by the game, a current level failure occurs

Copy Code code as follows:

Player = player (name: "Beto")
If Player.tracker.advanceToLevel (6) {
println ("Player is now in Level 6")
} else {
println ("Level 6 has not yet been unlocked")
}
Prints "Level 6 has not yet been unlocked"

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.