iOS development Language Swift Introduction---method

Source: Internet
Author: User
Tags instance method

iOS development language Swift Getting started serial-Methods

A method is a function that is associated with some particular type. Classes, structs, enumerations can define instance methods, and instance methods encapsulate specific tasks and functions for instances of a given type. Classes, structs, enumerations can also define type methods, and type methods are associated with the type itself. Type methods are similar to class methods in Objective-c.
The ability to define methods for structs and enumerations is 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. But in Swift, you can choose not only whether you want to define a class/struct/enumeration, but also the flexibility to define methods on the type you create (class/struct/enum).

Instance method (Instance Methods)

An instance method is a method that belongs to a particular class, struct, or instance of an enumeration type. Instance methods provide a way to access and modify instance properties, or provide functionality related to an instance's purpose, and support the functionality of the instance. The syntax of the instance method is exactly the same as the function, see function for details.
The instance method is written between the curly braces of the type to which it belongs. 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.
The following example defines a very simple class counter,counter that can be used to count the number of times an action occurs:

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

The counter class defines three instance methods:
Increment let the counter press one increment;
IncrementBy (Amount:int) to increment the counter by a specified integer value;
Reset resets the counter to 0.
Counter This class also declares a mutable attribute count, which is used to keep track of the current counter value.
Call an instance method with dot syntax (dot syntax), just as you would call a property:

let counter = Counter()// 初始计数值是0counter.increment()// 计数值现在是1counter.incrementBy(5)// 计数值现在是6counter.reset()// 计数值现在是0

The local parameter name of the method and the external parameter name (local and External Parameter Names for Methods) function arguments can have both a local name (used inside the function body) and an external name (used when calling the function). See the external parameter name of the function for details. The method parameter is the same (because the method is a function, but the function is associated with a type). However, the default behavior of the local and external names of methods and functions is not the same. The methods in Swift are very similar to the methods in Objective-c. Like in Objective-c, the name of a method in Swift usually uses a preposition to point to the first parameter of the method, such as With,for,by, and so on. This is how the IncrementBy method is in the previous example of the Counter class. The use of prepositions allows methods to be interpreted like a sentence when called. Unlike function parameters, Swift uses different default processing methods for the parameters of the method, which makes the method naming specification easier to write. Specifically, Swift defaults to only a local parameter name for the method's first parameter name; 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. Take a look at another version of this counter (which defines a more complex IncrementBy method):

class Counter {  var count: Int = 0  func incrementBy(amount: Int, numberOfTimes: Int) {    count += 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:

letisnow 15

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:

#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 is invoked in the form of a natural expression. Modifying the external parameter name of the method (modifying External Parameter name Behavior for Methods) is sometimes useful for providing an external parameter name for the first parameter of a method, although this is not the default behavior. 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. Each instance of the Self attribute type has an implied property called Self,self, which is exactly the same as 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:

funcincrement(){  self.count++}

In fact, you don't have to write self frequently in your code. Whenever you use a known property or method name in a method, if you do not explicitly write self,swift assume that you are referring to the property or method 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. The main scenario for using this rule is when an instance method has a parameter name that is the same as an instance's property name. In this case, the parameter name takes precedence and 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:

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 was to the right of the line where x = = 1.0" )}// output " this-is-to-the-right-of-the-line where x = = 1.0 " (this dot at x equals 1.0  the right side of this line)  

If you do not use the self prefix, Swift thinks that X used two times refers to a function parameter with the name X. In an instance method, modify the value type (modifying value Types from within Instance Methods) struct and enum 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 a struct or enumeration's properties in a specific method, you can choose the mutation (mutating) method, and 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. To use the mutation method, place the keyword mutating before the method's func keyword:

struct  point {var  x = 0.0 , y = 0.0  mutating Span class= "Hljs-keyword" >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 was now at (\ (somepoint.x), \ (SOMEPOINT.Y)) " ) //output "the point was now at (3.0, 4.0)"   

The point structure above defines a Variant method (mutating) Movebyx,movebyx used to move points. Instead of returning a new point, the Movebyx method modifies the point when it is called. The method definition is prefixed with the mutating keyword, which allows the method to modify the properties of the value type. Note: You cannot call a mutation method on a struct type constant, because the properties of a constant cannot be changed, even if you want to change the variable property of a constant, see storing properties and instance variables for details

let3.03.0)fixedPoint.moveByX(2.03.0)// this will report an error

In the mutation method, the self assignment (assigning to self within a 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 {  var x = 0.0, y = 0.0  func moveByX(deltaX: Double, y deltaY: Double) {    self = Point(x: x + deltaX, y: y + deltaY)  }}

The new version of the mutation method Movebyx creates a novel structure (its x and Y values are set to the target value). Calling this version of the method and invoking the last version of the final result is the same. The mutation method of an enumeration can set self to a different member of the same enumeration 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 now equals. High  ovenlight.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). The type Methods instance method is a method that is called by an instance of the type. You can also define a method called by the type itself, which is called a type method. Declare 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.
Attention:
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 explicitly included by the type it supports.
Type methods are called with the same point syntax as instance methods. However, you call this method at the type level, not at the instance level. The following is an example of how to invoke a type method on a SomeClass class:

class SomeClass {  class func someTypeMethod() {    // type method implementation goes here  }}SomeClass.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 (similar to what we did when we processed the instance properties and instance method parameters earlier). 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. The following example defines a struct named Leveltracker. It monitors the player's game development (different levels or stages of the game). This is a single player game, but it can also store game information for multiple players on the same device. At the beginning of the game, all game levels (except Level 1) are locked. Each time a player completes a level, this level unlocks all players on the device. The Leveltracker structure uses static properties and methods to monitor which level of the game has been unlocked. It also monitors the current level of each player.

struct Leveltracker {staticvarHighestunlockedlevel =1static Func Unlocklevel ( Level: Int) {ifLevel > Highestunlockedlevel {highestunlockedlevel = level}} static Func levelisunlocked (level:int) Bool {returnLevel <= Highestunlockedlevel}varCurrentLevel =1Mutating func Advancetolevel (level:int) Bool {ifLeveltracker.levelisunlocked (level) {CurrentLevel = levelreturn true}Else{return false}  }}

The

Leveltracker monitors the player's unlocked highest level. This value is stored in the static property Highestunlockedlevel. The
Leveltracker also defines two types of methods that work with the highestunlockedlevel. The first type method is Unlocklevel: Once the new level is unlocked, it updates the value of Highestunlockedlevel. The second type method is levelisunlocked: If a given level is already unlocked, it returns true. (Note: Although we do not use a leveltracker.highestunlockedlevel-like notation, this type method can still access the static property Highestunlockedlevel)
In addition to static properties and type methods, Leveltracker also monitors the progress of each player. It uses the instance attribute currentlevel to monitor the player's current level.
to facilitate the management of the CurrentLevel property, Leveltracker defines the instance method advancetolevel. This method checks whether the requested new level has been unlocked before updating the currentlevel. The Advancetolevel method returns a Boolean value to indicate whether the currentlevel can be set.
below, the player class uses Leveltracker to monitor and update each player's progress:

class  player  {var tracker = leveltracker   ()  let playername: Span class= "Hljs-type" >string  func completedlevel ( Level : int )  {leveltracker . Unlocklevel (level  + 1)  Tracker.advancetolevel   (level  + 1) } Init (name : String )  {playername = name}}   

The player class creates a new Leveltracker instance to monitor the development progress of this user. It provides the Completedlevel method: Once the player completes a specified level, it is called. This method unlocks the next level for all players and updates the current player's progress to the next level. (We ignored the Boolean value returned by Advancetolevel because it was known that the level was unlocked when Leveltracker.unlocklevel was called). You can also create an instance of the player for a new player and see what happens when the player finishes the hierarchy:

var"Argyrios")player.completedLevel(1)println("highest unlocked level is now \(LevelTracker.highestUnlockedLevel)")// 输出 "highest unlocked level is now 2"(最高等级现在是2)

If you create a second player and try to get it to start a level that is not unlocked by any player, the attempt to set the player's current level will fail:

"Beto")if player.tracker.advanceToLevel(6) {  println("player is now on level 6"else {  println("level 6 has not yet been unlocked")}// 输出 "level 6 has not yet been unlocked"(等级6还没被解锁)

iOS development Language Swift Introduction---method

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.