Home>

methodA specific type of associated function is called a method in swift.Classes are used to define methods in Objective C.Which provides users with flexibility as a swift language,Classes, structures and enumerations can be defined using methods.

Instance method

In the swift language, classes, structures, and enumerated instances are accessed through instance methods.

Functions provided by instance methods Access and modify instance properties The need for function association instances

Instance methods can be written in curly braces {}. It implicitly accesses properties of methods and class instances.When the type specifies a specific instance it calls to get access to that specific instance.

grammar

func funcname (parameters)->returntype
{statement1statement2 --- statement n
 return parameters
}

Example

class calculations {let a:intlet b:intlet res:int
 init (a:int, b:int) {self.a=a
 self.b=b
 res=a + b
 }
 func tot (c:int)->int {return res-c
 }
 func result () {
 println ("result is:\ (tot (20))")
 println ("result is:\ (tot (50))")}} let pri=calculations (a:600, b:300)
pri.result ()

When we run the above program using playground,Got the following results

result is:880
result is:850

The calculations class defines two instance methods:

init () is defined as adding two numbers a and b and storing its result in "res"

tot () is used to subtract "c" from the "res" value

Finally, the printed method of calculating the values ​​of a and b is called. Instance methods are accessed with "." Syntax

Local and external parameter names

swift functions describe local and global variable declarations.Similarly, the naming rules for Swift methods are similar to Objective C. But the characteristics of local and global parameter name declarations differ for functions and methods. The first argument to swift is to access the naming convention by the preposition names "with", "for" and "by".

swift provides the declaration as the name of the round parameter,Other parameter names are global parameter names,The first parameter is the method name.Here, the "no1" method is declared as a local parameter name. "no2" is used for global declarations,And accessed through the program.

class division {var count:int=0
 func incrementby (no1:int, no2:int) {
 count=no1/no2
 println (count))) let counter=division ()
counter.incrementby (1800, no2:3)
counter.incrementby (1600, no2:5)
counter.incrementby (11000, no2:3)

When we run the above program using playground,Got the following results

600
320
3666

External parameter names use the #and _ symbols

Although the swift method provides the first parameter name as a local declaration,The user must provide to modify the parameter name from local to global declaration.This can be done by prefixing the "#" symbol with the first parameter name.By doing this,The first parameter can be accessed globally throughout the module.

When the user needs to use the external name to access the following parameter names,The name of the method is overwritten with a "_" sign.

class multiplication {var count:int=0
 func incrementby (#no1:int, no2:int) {
 count=no1 * no2
 println (count))) let counter=multiplication ()
counter.incrementby (no1:800, no2:3)
counter.incrementby (no1:100, no2:5)
counter.incrementby (no1:15000, no2:3)

When we run the above program using playground,Got the following results

2400
500
45000

Self property in method

A method has an implicit property called "self" that is owned by all defined type instances.The "self" attribute is used to indicate the current instance-defined method.

class calculations {let a:intlet b:intlet res:int
 init (a:int, b:int) {self.a=a
 self.b=b
 res=a + b
 println ("inside self block:\ (res)")}
 func tot (c:int)->int {return res-c
 }
 func result () {
 println ("result is:\ (tot (20))")
 println ("result is:\ (tot (50))")}} let pri=calculations (a:600, b:300) let sum=calculations (a:1200, b:300)
</p>
<p>
pri.result ()
sum.result ()

When we run the above program using playground,Got the following results

inside self block:900
inside self block:1500
result is:880
result is:850
result is:1480
result is:1450

Modified instance method value types

In swift language structure and enumeration and value types cannot be changed by its instance methods.However, the swift language provides the flexibility to modify value types through "mutation" behavior.Mutations will make any changes in the example method,Change the method to its original form after the method is executed.In addition, a new instance of the "selft" attribute is created by its implicit function,Will replace existing methods after execution

struct area {var length=1var breadth=1
 func area ()->int {return length * breadth
 }
 mutating func scaleby (res:int) {
 length *=res
 breadth *=res
 println (length)
 println (breadth))} var val=area (length:3, breadth:5)
val.scaleby (3)
val.scaleby (30)
val.scaleby (300)

When we run the above program using playground,Got the following results

9
15
270
450
81000
135000

Different mutagenesis methods for the self property

The mutation method combines the "self" attribute with the method defined by the new instance.

struct area {var length=1var breadth=1
 func area ()->int {return length * breadth
 }
 mutating func scaleby (res:int) {self.length *=res
 self.breadth *=res
 println (length)
 println (breadth))} var val=area (length:3, breadth:5)
val.scaleby (13)

When we run the above program using playground,Got the following results

39
65

Type method

When a particular instance of a method is called,It calls an instance method and when a method calls a method of a particular type is defined as a "type method". The type method "class" is defined by the "func" keyword and structure,And enumerated methods are defined using the "static" keyword before the "func" keyword.

Type method invocation,By accessing "." Instead of calling a specific instance method,Examples and syntax are as follows:

classmath {class func abs (number:int)->int {if number<0 {return (-number)} else {return number
 }}} struct absno
{static func abs (number:int)->int {if number<0 {return (-number)} else {return number
 })) letno=math.abs (-35) let num=absno.abs (-5)
</p>
<p>
println (no)
println (num)

When we run the above program using playground,Got the following results

35
5

AttributesThe swift language provides classes,Enumerated or structured attributes with associated values.Attributes can be further divided into storage attributes and calculated attributes.

Difference between storage performance and calculated properties

These two storage and calculation properties are associated with instance types.When an attribute is associated with its type value,Then it is defined as a "type attribute". Stored and calculated attributes are often associated with a particular type of instance.However, attributes can also be associated with the type itself.Such attributes are known types of attributes. Attribute observers are also used

Observe stored attribute values

Observe the properties inherited by the child class from the parent

Storage attributes

swift introduces the concept of stored properties to store constants and variables instances.The properties of constant storage are defined by the "let" keyword and the properties of stored variables are defined by the "var" keyword.

Provides "default value" in the definition stored property

Users can initialize and modify initial values ​​during initialization

structnumber {var digits:intlet pi=3.1415} var n=number (digits:12345)
n.digits=67
</p>
<p>
println ("\ (n.digits)")
println ("\ (n.pi)")

When we run the above program using playground,Got the following results

67
3.1415

Considering the code above,Such as the following line:

let pi=3.1415

Here, the variable pi is initialized to store the attribute value using the instance pi=3.1415. So, whenever the instance is called it will hold a separate value:3.1415.

Another way,Stored attributes may be constant structures.The entire instance of such a structure will be considered "storage of constant attributes".

structnumber {var digits:intlet numbers=3.1415} var n=number (digits:12345)
n.digits=67
</p>
<p>
println ("\ (n.digits)")
println ("\ (n.numbers)")
n.numbers=8.7

When we run the above program using playground,Got the following results

error:cannot assign to "numbers" in "n"
n.numbers=8.7

Reinitialize "Number" to 8.7 and it will return an error message indicating that "Number" was declared as a constant.

Lazy storage attributes

swift provides so-called "lazy storage properties", and when a variable is first initialized it does not calculate the initial value. Before the variable declaration of the "lazy" modifier,Think of it as a lazy storage property.

The delay attribute is used:

To delay the creation of an object.

When properties are dependent on other parts of a class,Ie:not yet known

class sample {
 lazy varno=number () //`var` declaration is required.} class number {var name =" swift "} var firstsample=sample ()
println (firstsample.no.name)

When we run the above program using playground,We get the following results

swift

Instance variable

In objective c, storage attributes must also have instance variables for backup purposes,Stores the value of the property declaration in storage.

swift integrates these concepts into a "stored property" declaration. Instead of having a corresponding instance variable and backup value "storage attribute", which contains all the information about the variable attribute defined by a variable name in one place,Data types and memory management functions.

Calculated attributes

Instead of storing calculated property values, a getter and an optional setter are provided indirectly to retrieve and set other properties and values.

class sample {var no1=0.0, no2=0.0var length=300.0, breadth=150.0var middle:(double, double) {get {return (length/2, breadth/2)} set (axis) {
 no1=axis.0- (length/2)
 no2=axis.1- (breadth/2)})) var result=sample ()
println (result.middle)
result.middle=(0.0, 10.0)
</p>
<p>
println (result.no1)
println (result.no2)

When we run the above program using playground,We get the following results

(150.0, 75.0)
-150.0
-65.0

When a calculated property leaves a new value undefined, the default value will be set for a specific variable.

Calculated attributes are read-only

Read-only properties in computed properties are defined as getters, but not setters. It is always used to return a value.Variables are accessed using the "." Syntax,It cannot be set to other values.

class film {var head="=" var duration=0.0var metainfo:[string:string] {return ["head":self.head, "duration":"\ (self.duration)"]}} var movie=film ()
movie.head="swift properties"
movie.duration=3.09
</p>
<p>
println (movie.metainfo ["head"]!)
println (movie.metainfo ["duration"]!)

When we run the above program using playground,We get the following results

swift properties
3.09

Calculated Properties Property Observer

Use property observers in swift to observe and set property value responses. The property observer is called every time the property value is set. In addition to lazy storage attributes,We can "override" methods by adding property observers to "inherit" properties.

Before storing values-willset

After storing the new value-didset

When a property is set in the initializer willset and didset observers cannot be called.

classsamplepgm {var counter:int=0 {
 willset (newtotal) {
 println ("total counter is:\ (newtotal)")}
 didset {if counter>oldvalue {
 println ("newly added counter \ (counter-oldvalue)")}}}} letnewcounter=samplepgm () newcounter.counter=100newcounter.counter=800

When we run the above program using playground,We get the following results

total counter is:100
newly added counter 100
total counter is:800
Newly added counter 700

Local and global variables

Declarations of local and global variables for computed and observed properties.

Type attribute

The attribute definition type definition has braces {}, and the scope of the variable is also defined earlier.To define the value type use the "static" keyword and the type of the class use the "class" keyword.

grammar

structstructname {staticvar storedtypeproperty="" staticvar computedtypeproperty:int {//return an int value here}} enumenumname {staticvar storedtypeproperty="" staticvar computedtypeproperty:int {//return an int value here}} classclassname {classvar computedtypeproperty:int {//return an int value here}}

Querying and setting properties

Similar to instance property type property query and setting,Just use the "." Syntax instead of pointing to the type of the instance.

structstudmarks {staticlet markcount=97staticvar totalcount=0varinternalmarks:int=0 {
 didset {ifinternalmarks>studmarks.markcount {internalmarks=studmarks.markcount
 } ifinternalmarks>studmarks.totalcount {studmarks.totalcount=internalmarks}}} var
</p>
<p>
stud1mark1.internalmarks=98
println (stud1mark1.internalmarks)
</p>
<p>
stud1mark2.internalmarks=87
println (stud1mark2.internalmarks)

When we run the above program using playground,We get the following results

97
87
  • Previous Introduction to basic shortcuts and configuration for Python IDE PyCharm
  • Next Method for determining special IP address using InetAddress class in Java programming