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
,Counter
Can 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 }}
Counter
Class defines three instance methods:
increment
Increase the number of counters by one;
incrementBy(amount: Int)
Increase the number of counters by a specified integer;
reset
Reset the counter to 0.
Counter
This class also declares a variable attributecount
To 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
,by
And so on. PreviousCounter
Class ExampleincrementBy
This 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 complexincrementBy
Method ):
class Counter { var count: Int = 0 func incrementBy(amount: Int, numberOfTimes: Int) { count += amount * numberOfTimes }}
incrementBy
The method has two parameters:amount
AndnumberOfTimes
. By default, SWIFT only setsamount
As a local name,numberOfTimes
It 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: BecauseincrementBy
We 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, similarnumberOfTimes
Write 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.
self
Attribute
Each instance of the type has an implicit attribute calledself
,self
It is equivalent to the instance itself. You can use this implicitself
Attribute to reference the current instance.
In the above exampleincrement
The 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 methodself
Swift assumes that you are referring to the attributes or methods of the current instance. This assumption aboveCounter
As shown in the following figure:Counter
Which 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 useself
Attribute to distinguish between parameter names and attribute names.
In the following example,self
Elimination Method Parametersx
And instance attributesx
Ambiguity:
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 useself
Prefix, which swift considers to be used twicex
All 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 implicitself
Attribute value is assigned to a new instance. The new instance will replace the original Instance after the method is completed.
To useMutation
Method.mutating
Put in Methodfunc
Before 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 abovePoint
Struct defines a mutating Method)moveByX
,moveByX
Used to move a vertex.moveByX
This vertex is modified when the method is called, instead of returning a new vertex. Addmutating
Keyword, 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.self
A brand new instance. AbovePoint
The 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 MethodmoveByX
A 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 canself
Set 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 callnext
The 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 Methodfunc
Keyword added before the keywordclass
Declare the struct and enumeration type methods infunc
Keyword 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 howSomeClass
Class call type method example:
class SomeClass { class func someTypeMethod() { // type method implementation goes here }}SomeClass.someTypeMethod()
In the method body of the type method,self
Point to the type itself, rather than a type instance. For struct and enumeration, this means you can useself
To 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 definesLevelTracker
Struct. 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.LevelTracker
Struct 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 } }}
LevelTracker
Monitors the highest level of unlocked players. This value is stored in static properties.highestUnlockedLevel
.
LevelTracker
Two types of methods andhighestUnlockedLevel
Work 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.highestUnlockedLevel
This method can still access static attributes.highestUnlockedLevel
)
In addition to static attributes and type methods,LevelTracker
It also monitors the progress of each player. It uses instance attributescurrentLevel
To monitor the player's current level.
For ease of ManagementcurrentLevel
Attribute,LevelTracker
Instance method definedadvanceToLevel
. This method will be updated incurrentLevel
Check whether the requested new level has been unlocked.advanceToLevel
The method returns a Boolean value to indicate whether a value can be set.currentLevel
.
Below,Player
Class usageLevelTracker
To 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 }}
Player
Class to create a newLevelTracker
Instance to monitor the user's development progress. It providescompletedLevel
Method: 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 ignoredadvanceToLevel
Returns a Boolean value becauseLevelTracker.unlockLevel
The level has been unlocked ).
You can also createPlayer
And 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