Swift Chinese manual-methods

Source: Internet
Author: User
Method

MethodIs a function associated with certain types. You can define instance methods for classes, structs, and enumerations. instance methods encapsulate specific tasks and functions for a given type of instances. Class, struct, and enumeration can also define the type method. The type method is associated with the type itself. The type method is similar to the class methods in objective-C.

Struct and enumeration can be defined as one of the main differences between SWIFT and C/objective-C. In objective-C, a class is the only type that can define a method. However, in swift, you can choose not only to define a class/struct/enumeration, but also flexibly define methods on the type (Class/struct/enumeration) you create.

Instance method

Instance methodIs a method of a specific class, struct, or enumeration type instance. The instance method provides methods for accessing and modifying instance attributes, or provides functions related to the instance's purpose, and supports the instance's functions.

The instance method should be written between the braces of its type. The instance method can implicitly access all other instance methods and attributes of its type. An instance method can only be called by a specific instance of the class to which it belongs. The instance method cannot be called without the existing instance.

The following example defines a very simple classCounter,CounterCan be used to count the number of times an action occurs:

class Counter {  var count = 0  func increment() {    count++  }  func incrementBy(amount: Int) {    count += amount  }  func reset() {    count = 0  }}

CounterClass defines three instance methods:

  • incrementIncrease the number of counters by one;
  • incrementBy(amount: Int)Increase the number of counters by a specified integer;
  • resetReset the counter to 0.

CounterThis class also declares a variable attributecountTo keep track of the current counter value.

Like calling properties, call the instance method using DOT Syntax:

Let counter = counter () // The initial count value is 0 counter. increment () // The Count value is now 1 counter. incrementby (5) // The Count value is now 6 counter. reset () // The Count value is now 0

Local parameter name and External Parameter Name of the Method

A function parameter can have a local name (used inside the function body) and an external name (used when a function is called ).

Methods In swift are very similar to those in objective-C. Like in objective-C, the method name in swift usually points to the first parameter of the method with a prefix, for example:with,for,byAnd so on. PreviousCounterClass ExampleincrementByThis is the way. The use of prepositions allows a method to be interpreted as a sentence when called. Unlike function parameters, swift uses different default processing methods for method parameters, which makes it easier to write method naming rules.

Specifically, by default, SWIFT only gives the first parameter name of the method a local parameter name. By default, it also gives the second and subsequent parameter names a local parameter name and an external parameter name. This Convention is compatible with typical naming and calling conventions, and is very similar to when you write objective-C methods. This Convention also removes the need to limit parameter names when calling Expression methods.

Take a look at the followingCounter(It defines a more complexincrementByMethod ):

class Counter {  var count: Int = 0  func incrementBy(amount: Int, numberOfTimes: Int) {    count += amount * numberOfTimes  }}

incrementByThe method has two parameters:amountAndnumberOfTimes. By default, SWIFT only setsamountAs a local name,numberOfTimesIt is regarded as a local name and an external name. Call this method as follows:

let counter = Counter()counter.incrementBy(5, numberOfTimes: 3)// counter value is now 15

You do not need to define an external variable name for the first parameter value: BecauseincrementByWe can clearly see its role. However, the second parameter must be limited by an external parameter name to define its role when the method is called.

This default action can be used as a valid method, similarnumberOfTimesWrite a ticket (#):

func incrementBy(amount: Int, #numberOfTimes: Int) {  count += amount * numberOfTimes}

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 will be called as a natural expression.

External Parameter Name of the modification method

Sometimes it is very useful to provide an external parameter name for the first parameter of the method, although this is not the default behavior. You can add an explicit external name or use (#) As the prefix of the first parameter to use this local name as an external name.

If you do not want to provide an external name for the second and subsequent parameters of the method, you can use the underline (_) As the explicit external name of the parameter, which overwrites the default behavior.

selfAttribute

Each instance of the type has an implicit attribute calledself,selfIt is equivalent to the instance itself. You can use this implicitselfAttribute to reference the current instance.

In the above exampleincrementThe method can also be written as follows:

func increment() {  self.count++}

In fact, you don't have to write frequently in your codeself. Whenever you use a known property or method name in a methodselfSwift assumes that you are referring to the attributes or methods of the current instance. This assumption aboveCounterAs shown in the following figure:CounterWhich of the three instance methods in iscount(Insteadself.count).

The main scenario of using this rule is that a parameter name of the instance method is the same as an attribute name of the instance. In this case, parameter names have priority and must be referenced in a more rigorous manner. You can useselfAttribute to distinguish between parameter names and attribute names.

In the following example,selfElimination Method ParametersxAnd instance attributesxAmbiguity:

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 line where x = 1.0 ")} // output "this point is to the right of the line where x = 1.0" (This point is on the right of the Line X equals 1.0)

If you do not useselfPrefix, which swift considers to be used twicexAll refer tox.

Modify the value type in the instance method

Struct and enumeration areValue Type. Generally, the attribute of the value type cannot be modified in its instance method.

However, if you really need to modify the struct or enumeration attributes in a specific method, you can chooseMutating)In this way, the method can change its attributes from inside the method, and any changes it makes will be kept in the original structure at the end of the method. You can also give it an implicitselfAttribute value is assigned to a new instance. The new instance will replace the original Instance after the method is completed.

To useMutationMethod.mutatingPut in MethodfuncBefore the Keyword:

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 at (\ (somepoint. x), \ (somepoint. y) ") // output" The point is now at (3.0, 4.0 )"

The abovePointStruct defines a mutating Method)moveByX,moveByXUsed to move a vertex.moveByXThis vertex is modified when the method is called, instead of returning a new vertex. AddmutatingKeyword, so that the method can modify the attribute of the value type.

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

let fixedPoint = Point(x: 3.0, y: 3.0)fixedPoint.moveByX(2.0, y: 3.0)// this will report an error

Assign a value to self in the Mutation Method

The mutation method can be assigned to implicit attributes.selfA brand new instance. AbovePointThe example can be rewritten 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)  }}

New Version Variation MethodmoveByXA new structure is created (both its x and y values are set as the target values ). The method for calling this version is the same as that for calling the previous version.

The enumerated variation method canselfSet to different members of the same enumerated type:

Enum tristateswitch {case off, low, high mutating func next () {Switch self {case off: Self = low case low: Self = high case high: self = off }}var ovenlight = tristateswitch. lowovenlight. next () // ovenlight is now equal. highovenlight. next () // ovenlight is now equal. off

The preceding example defines an enumeration of three-state switches. Each callnextThe switch is in different power status (Off,Low,High.

Type Method

The instance method is called by a type instance. You can also define the method called by the type itself. This method is calledType Method. Declare the type method of the class, in the MethodfuncKeyword added before the keywordclassDeclare the struct and enumeration type methods infuncKeyword added before the keywordstatic.

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, struct, and enumeration: Each type method is explicitly included by the supported types.

The type method is called using the dot syntax like the instance method. However, you call this method at the type level, rather than at the instance level. The following describes howSomeClassClass call type method example:

class SomeClass {  class func someTypeMethod() {    // type method implementation goes here  }}SomeClass.someTypeMethod()

In the method body of the type method,selfPoint to the type itself, rather than a type instance. For struct and enumeration, this means you can useselfTo eliminate ambiguity between static attributes and static method parameters (similar to what we did before processing instance attributes and instance method parameters ).

In general, any undefined method and attribute names will come from methods and attributes of another type level in this class. One type method can call the name of another type method in this class, without adding the type name prefix before the method name. Similarly, the struct and enumeration type methods can directly access static properties through the static property name without the type name prefix.

The following example definesLevelTrackerStruct. It monitors the game development of players (different levels or stages of the game ). This is a single player, but it can also store Game Information of multiple players on the same device.

At the beginning of the game, all game levels (except level 1) were locked. Each time a player completes a level, it unlocks all players on the device.LevelTrackerStruct uses static attributes and methods to monitor which level of the game has been unlocked. It also monitors the current level of each player.

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    }  }}

LevelTrackerMonitors the highest level of unlocked players. This value is stored in static properties.highestUnlockedLevel.

LevelTrackerTwo types of methods andhighestUnlockedLevelWork together. The first type method isunlockLevel: Once the new level is unlocked, it will updatehighestUnlockedLevel. The second type method islevelIsUnlocked: If a given level has been unlocked, it returnstrue. (Note: although we have not used a similarLevelTracker.highestUnlockedLevelThis method can still access static attributes.highestUnlockedLevel)

In addition to static attributes and type methods,LevelTrackerIt also monitors the progress of each player. It uses instance attributescurrentLevelTo monitor the player's current level.

For ease of ManagementcurrentLevelAttribute,LevelTrackerInstance method definedadvanceToLevel. This method will be updated incurrentLevelCheck whether the requested new level has been unlocked.advanceToLevelThe method returns a Boolean value to indicate whether a value can be set.currentLevel.

Below,PlayerClass usageLevelTrackerTo monitor and update the progress of each player:

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  }}

PlayerClass to create a newLevelTrackerInstance to monitor the user's development progress. It providescompletedLevelMethod: Call it once the player completes a specified level. This method unlocks the next level for all players and updates the progress of the current player to the next level. (We ignoredadvanceToLevelReturns a Boolean value becauseLevelTracker.unlockLevelThe level has been unlocked ).

You can also createPlayerAnd then check the player's completion level:

VaR player = player (name: "argyrios") player. completedlevel (1) println ("highest unlocked level is now \ (leveltracker. highestunlockedlevel) ") // output" highest unlocked level is now 2 "(the highest level is 2)

If you create a second player and try to start a level that is not unlocked by any players, this attempt to set the current level of players will fail:

Player = player (name: "Beto") if player. tracker. advancetolevel (6) {println ("player is now on Level 6")} else {println ("Level 6 has not yet been unlocked ")} // output "Level 6 has not yet been unlocked" (Level 6 is not unlocked yet)
Swift QQ Group

Swift mutual communication QQ group: 74512850, so that fans can make progress together! The full Chinese PDF file is available in the group!

Click the link to join the group [swift development mutual assistance]: http://jq.qq.com /? _ WV = 1027 & K = nwgksv

Chinese manual navigation

Blog: Click to enter the navigation bar

GitHub: Click to enter the navigation bar

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.