Explain the concept of methods and attributes in Swift programming _swift

Source: Internet
Author: User
Tags abs constant instance method naming convention

Method
specific types of associated functionality in Swift are called methods. Classes in objective C are used to define methods, which provide flexibility for users as Swift language, classes, structs, and enumerations to define usage methods.

Instance method
In the Swift language, classes, structs, and enumeration instances are accessed through instance methods.

    • The functionality provided by the instance method
    • Accessing and modifying instance properties
    • The need for a function association instance

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

Grammar

Copy Code code as follows:

Func funcname (Parameters)-> returntype
{Statement1statement2---Statement N
return parameters
}

Example
Copy Code code as follows:

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)")}}let pri = calculations (a:600, b:300)
Pri.result ()

When we use playground to run the above program, we get 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 results in ' res '

Tot () is used to subtract ' C ' from the ' res ' value

Finally, you call the print value method for the calculation a and B. instance method to access the "." Syntax

Local and external parameter names
The Swift function describes local and global variable declarations. Similarly, the Swift method's naming convention is similar to objective C. However, the attributes of local and global parameter name declarations are different for functions and methods. Swift's first argument is to access the naming convention by the preposition name ' with ', ' for ' and ' by '.

Swift provides the declaration as the name of the number parameter, the other parameter name is the global parameter name, and 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 is accessed through this program.

Copy Code code as follows:

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 use playground to run the above program, we get the following results

3666

External parameter names using # and _ Symbols
Although the Swift method provides the first parameter name as a local declaration, the user must provide a change to the parameter name from local to global declaration. This can be done by using the ' # ' symbol prefix with the first parameter name. By doing this, the first parameter can be accessed as a global throughout the module.

When the user needs to use an external name to access the following parameter names, the method's name is overwritten with the "_" symbol.

Copy Code code as follows:

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 use playground to run the above program, we get the following results

2400
45000

Self property in method
A method has an implicit property called "Self", all of which are defined by the type instance. The self attribute is used to represent the method of the current instance definition.

Copy Code code as follows:

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 being: \ Tot ()")}}let pri = calculations (a:600, b:300) Let sum = Calculations (a:1200, b:300)

Pri.result ()
Sum.result ()


When we use playground to run the above program, we get the following results

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

Modified instance method value type
In Swift language structures and enumerations 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 allow any change in the instance method to return the method to its original form after execution. In addition, a new instance of the "Selft" property is created with its implicit function, and execution replaces the existing method

Copy Code code as follows:

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 use playground to run the above program, we get the following results

9
270
450
81000
135000

Different mutagenesis methods of Self properties
The mutation method is assigned to the method defined by the new instance, combined with the "self" attribute.

Copy Code code as follows:

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 use playground to run the above program, we get the following results


65

Type method
When a specific instance of a method is called, it calls an instance method and when a method calls a method of a particular type it is defined as a "type method." Type method "Class" is defined by the "func" keyword and struct definition, and the "static" keyword before the "func" keyword by the enumeration method.

Type method invocation, which is done by accessing '. ' Instead of invoking a specific instance of the method, examples and syntax are as follows:

Copy Code code as follows:

Classmath{class func abs (number:int)->int{if number <0{return (-number)}else{return
}}}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)

println (NO)
println (num)


When we use playground to run the above program, we get the following results


5 km

Property
The Swift language provides properties for a class, enumeration, or struct-associated value. Attributes can be further divided into storage properties and computed properties.

The difference between storage performance and computed properties

These two storage and computed properties are associated with the instance type. When an attribute is associated with its type value, it is defined as "type attribute." Properties that are stored and evaluated are typically associated with an instance of a particular type. However, a property can also be associated with the type itself. Such a property is a property of a known type. Attribute observers are also used

Observe the stored property values

To observe the attributes inherited by a subclass from the parent

Storage properties
Swift describes the stored attribute concepts used to store instances of constants and variables. The properties of a constant store are defined by the ' let ' keyword and the properties of a stored variable are determined by the ' var ' keyword.

The property that defines the store provides a "default value"

The user can initialize and modify the initial value during initialization

Copy Code code as follows:

Structnumber{var digits:intlet pi =3.1415}var n =number (digits:12345)
N.digits =67

println ("\ (n.digits)")
println ("\ (N.PI)")


When we use playground to run the above program, we get the following results


3.1415

Consider the code above, as in the following line:

Copy Code code as follows:

Let pi = 3.1415

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

Alternatively, the stored property might be a constant structure. The entire instance of this structure is considered to be a "store of constant properties".

Copy Code code as follows:

Structnumber{var Digits:intlet numbers =3.1415}var n =number (digits:12345)
N.digits =67

println ("\ (n.digits)")
println ("\ (n.numbers)")
N.numbers =8.7


When we use playground to run the above program, we get the following results

Error:cannot assign to ' numbers ' in ' n '
n.numbers = 8.7

Reinitialize ' number ' is 8.7, which returns an error message indicating that "number" is declared as constant.

Lazy Storage Properties
Swift provides the so-called "lazy storage attribute", which does not compute the initial value when the variable is initialized for the first time. The "lazy" modifier has a variable declaration before it is used as a lazy storage property.

Deferred attributes are used:

To delay the creation of the object.

When an attribute is dependent on another part of a class, that is: not yet known

Copy Code code as follows:

Class Sample {
Lazy varno= Number ()//' var ' declaration is required.} Class Number {var name = "Swift"}var firstsample = sample ()
println (Firstsample.no.name)

When we use playground to run the above program, we get the following results
Swift
Instance variables
In objective C, the storage attribute must also have an instance variable for backup purposes, stored in the value of the stored property declaration.

Swift integrates these concepts into a "stored attribute" declaration. Instead of having a corresponding instance variable and a backup value ' storage attribute ', it contains all information integration, data type, and memory management functions for variable attributes defined by a location of the variable name.

Calculation properties
Instead of storing the computed property value provides a getter and an optional setter to retrieve and set other properties and values indirectly.

Copy Code code as follows:

Class Sample {var No1 =0.0, No2 =0.0var length =300.0, breadth =150.0var Middle: (double,double) {Get{return (LENGTH/2, Brea DTH/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)

println (RESULT.NO1)
println (RESULT.NO2)


When we use playground to run the above program, we get the following results

(150.0, 75.0)
-150.0
-65.0

When the computed property leaves a new value that is undefined the default value is set for a particular variable.

Computed property is read-only property
The read-only property of the computed property is defined as getter, but not setter. It is always used to return a value. Variables are accessed by using the '. ' syntax, but cannot be set to a different value.

Copy Code code as follows:

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

println (movie.metainfo["Head"]!)
println (movie.metainfo["duration"]!)


When we use playground to run the above program, we get the following results

Swift Properties
3.09

Compute Property Property Observer
Use attribute observers in swift to observe and set property value responses. When the property value is set for each property observer is invoked. In addition to the lazy storage properties, we can override the method by adding the Property viewer Inheritance property.

Before storing the value-willset

After the new value is stored-didset

When an attribute is set at initialization Willset and Didset observers cannot invoke.

Copy Code code as follows:

Classsamplepgm{var counter:int=0{
Willset (newtotal) {
println ("Total Counter are: \ (newtotal)")}
Didset{if counter > OldValue {
println ("newly Added Counter \ (counter-oldvalue)")}}}}letnewcounter=samplepgm () Newcounter.counter = 100newcounter.counter =800

When we use playground to run the above program, we get the following results

Total Counter is:100
newly Added Counter total
Counter is:800 newly Added Counter
700

Local and global variables
For statements that compute and observe property local and global variables.

Type properties
The Property Definition type definition section has curly braces {}, and the scope of the variable is also defined previously. To define a value type use the "class" keyword with the "static" keyword and the type of the class.

Grammar

Copy Code code as follows:

Structstructname{staticvar Storedtypeproperty = "" Staticvar computedtypeproperty:int{//return a Int value here}} Enumenumname{staticvar Storedtypeproperty = "" Staticvar computedtypeproperty:int{//return a Int value here}} Classclassname{classvar computedtypeproperty:int{//return a Int value here}}

Querying and setting properties
Similar to instance property Type property queries and settings, just use the "." syntax instead of pointing to the type of the instance.
Copy Code code as follows:

Structstudmarks{staticlet markcount =97staticvar totalcount =0varinternalmarks:int=0{
Didset {ifinternalmarks>studmarks.markcount {Internalmarks=studmarks.markcount
}ifinternalmarks>studmarks.totalcount {studmarks.totalcount =internalmarks}}}}var stud1Mark1 =StudMarks () var STUD1MARK2 =studmarks ()

Stud1mark1.internalmarks=98
println (Stud1mark1.internalmarks)

stud1mark2.internalmarks=87
println (Stud1mark2.internalmarks)


When we use playground to run the above program, we get the following results


87

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.