iOS development swift-Properties and methods

Source: Internet
Author: User

First, definition of Class

The difference between swift and objective-c definition classes

OBJECTIVE-C: typically requires 2 files, 1. h Declaration files and 1. m implementation files

Swift: only 1. Swift files required

Definition format for classes in Swift

1 class name  {2     //... Properties and Method 3}

Second, the attribute

1. What is a property

Properties in Swift, similar to member variables in other object-oriented languages

2. Classification of attributes

According to the official documentation, attributes can be divided into the following types of

(1) Storage attributes (Stored properties)

(2) Calculated attributes (Computed properties)

(3) Type attribute (type properties)

3. Storage Properties

1) Brief description

Store Properties: A stored property is a variable or constant stored in an object (instance)

Storing properties similar to member variables in other object-oriented languages

1 class Person {2     var age:int = $     var height:double = 0.04 let life     = 15}

Description

3 storage properties defined in person class

2 Variables Store Properties: Age of type int, height of double type

1 Constant Storage properties: int type of life

The system does not automatically initialize the above 3 storage properties and requires manual initialization

2) Read and write storage properties

How do I read and write storage properties?

You can read and write the stored properties of an object directly through the dot operator (.)

class Person {    11 =println("      P's life is \ (P.life), P's age is \ (p.age)")
View Code

Description

Line 5th: Create Person Object

Line 6th: Assign a value to the age property of the object P

Line 7th: Accessing the Life attribute value and the Age property value of the object P

3) Deferred storage properties

What is the deferred storage attribute?

Deferred storage properties are properties that are initialized the first time they are used

Using @lazy to identify a deferred storage property

1 class Person {2     @lazy var dog:dog = Dog () 3}4 var p = person () 5 println (P.dog)

Description

The Dog property is not initialized until the 5th line of code is executed to actually create the dog object

Use of deferred storage properties Note: The deferred store property must be a variable and cannot be a constant

The benefit of delaying storage properties: to allow some resources to be loaded again, to avoid unnecessary waste of resources

4. Calculating properties

(1) What is a computed property

Unlike storage properties, computed properties do not store values directly, but rather provide get and set

Get: The process used to take a value and encapsulate a value

Set: The process used to set values and encapsulate values

(2) Code example:

classSquare {//width of the squarevar width:double =0.0    //the perimeter of a squarevar girth:double {Get {            //perimeter = width * 4                returnWidth *4        }        Set(Newgirth) {//width = circumference/4width = Newgirth/4        }    }}
View Code

Examples of computed properties:

Description

The 3rd line of code: Call the Girth property of get, the output is 40

Line 4th: Call the set of the girth property and pass 200 to the Newgirth parameter

The 5th line of code: the output is 50

(3) Simple set

Set can also not intentionally specify the parameter name of the new value, the default parameter name of the new value is called NewValue

var girth:double {    get  {        return4    }    set  {         4    
View Code

Description

When executing the 9th line of code: The value of NewValue in line 6th is 200

(4) Use of calculated attributes note

1) Because the value of the computed property is not fixed, you can only use the Var modifier to evaluate the property, not the Let

class Square {    var girth:double {        get  {            return  girth        }         Set (Newgirth) {            = Newgirth        }     }}
View Code

Description: The above code throws a dead loop, the 4th line of code raises a loop call get, and the 7th line of code throws a loop call set.

2) A property cannot be both a storage property and a computed property

class Square {    20.0  {        get  {            return10.0         }        set() {                    }     }}
View Code

Description: The above code is wrong

(5) Read-only computed properties

What is a read-only computed property? Provides only get, no set computed properties

class Square {    0.0    var girth:double {        get  {            return}  4        }    =
View Code

Description: The 10th line of code will error

Shorthand for read-only computed properties. Read-only computed properties can omit the Get keyword

class Square {    0.0    var girth:double {        return4    =   $
View Code

Description: The 8th line of code will error

5. Type properties

(1) What is a type attribute?

Properties that are decorated with the class keyword are type attributes, or class properties

Class-Modified type properties can only be computed properties, not storage properties

code example:

1 class Circle {2     class var pi:double  {3         return 3.144     }5}

Description: The property pi, defined by line 2nd, is a Type property

(2) Characteristics of type attributes

A class will only have one copy, and multiple instance objects of the class share the only copy

Use of Type property: The Type property does not depend on an object and therefore is accessed using the class name

println (CIRCLE.PI)

Third, Property monitor

1. What is a property monitor?

Sometimes, you need to respond when a property value is modified, in which case you can use the property monitor

Property monitor, you can monitor the modification process of property values

The computed attribute can listen directly to the change of the property value in the set, and the stored property has no set

You can add Willset and didset two property monitors for storage properties

(1) Willset:

Called before a new property value is set

The new attribute value is passed in as a parameter, and the parameter name is newvalue by default

(2) Didset:

Called after a new property value has been set

The old property values are passed in as arguments, and the parameters are oldvalue by default.

2. Code examples

class Square {    0.0  {        willset {            println ("willset---\ (newvalue) " )        }        didset {            println ("didset---\ (oldValue)")        }     =Ten
View Code

Printing results:

Willset---10.0

Didset---0.0

3. Use note

class Square {    0.0  {        willset {}          }    =10  println (s.width)
View Code

Code Description:

Willset and Didset are not called during property initialization and are called only when the value of the property is set outside the initialization

Initialization of the 2nd line of code does not cause calls to Willset and Didset

Assignment of the 8th line of code will cause calls to Willset and Didset

If you assign a value to a property in the Didset monitor, this value replaces the previously set value

Line 4th assigns a value to the Width property again, overwriting the value assigned to line 8th, so the output of line 9th is 20.

Willset, Didset, and set, get cannot coexist

Iv. simple description of the method

As with other object-oriented languages, the methods in swift can be divided into 2 categories:

(1) Example method (Instance Methods)

In OC, the instance method starts with a minus sign (-)

(2) Type method (Type Methods)

In OC, the type method starts with a plus sign (+)

V. Examples and methods

1. What is an instance method?

Instance method: Is a method that can only be called with an object instance, or it can be called an object method

The syntax of an instance method is basically the same as a function

2. code example:

class Dog {    func run () {        println ("dog--->run")    = Dog () D.run ()
View Code

Description

Line 2nd defines a run method

Line 7th calls the Run method: The calling method is much like the calling function, and the format is "object name. Method Name (parameter)"

Vi. parameters of the method

(1) The parameters of the method and function are somewhat different, by default

The 1th parameter name of a method is just a local parameter name

The other parameter names of the method (except for the 1th parameter name) are both local and external parameter names

class Calculator {    , Int {        return num1 + num2    = Calculator () c.sum ( /c8>)
View Code

Description

NUM1 is only a local parameter name, NUM2 is both a local parameter name and an external parameter name

Equivalent to Func sum (num1:int, #num2: int), int

(2) You can add an underscore in front of the parameter name to remove the default external parameter name

class Calculator {    , Int {        return num1 + num2    = Calculator () c.sum ( /c8>)
View Code

Description: NUM1, num2 are only local parameter names, not external parameter names

(3) You can also add an external parameter name to the 1th parameter

class Calculator {    , Int {        return num1 + num2    =Ten )
View Code

Description: NUM1, num2 is both a local parameter name and an external parameter name

Vii. Types of methods

1. What is a type method?

Methods that are modified by the keyword class, also known as "class methods"

1 class Calculator {2     class func sum (Num1:int, num2:int), Int {3         return NUM1 + num24}5}6 calculato     R.sum (Ten, num2:20)

Description

Line 2nd defines a type method

The characteristics of a type method: Invoking a type method directly with a class, cannot invoke a type method with an object

Line 6th invokes the type method, in the form "class name. Method Name (parameter)"

Note: The method name of the type method and the instance method can be the same

class Calculator {    class func sum (num1:int, num2:int), Int {        return num1 +
   
     num2    }    ,
     Int {        
    return num1 +
     num2    }}calculator.sum ( 
    Ten 
     - 
     =
     Calculator () c.sum (
    ten
    )
   
View Code

Description

Line 2nd defines the type method and the instance method defined by line 5th: The same as the method name

Line 9th uses the class invocation type method

Line 11th using an object to invoke an instance method

Viii. Self

1. Brief description

Within each method, there is an implicit property of self, which is essentially consistent with the use of self in objective-c.

What does self represent? Who calls this method, self represents who

(1) In an instance method: Self represents an object that invokes a method

(2) In a type method: Self represents a class that invokes a method

2. Code examples

class Person {    class  func run () {        println ("class func run" )    }    func run () {        println ("func run")    }     class  func Test () {        self.run ();    }    Func Test () {        self.run ();     = Person () p.test () person.test ( )
View Code

The output of the program is:

Func Run

class Func Run

iOS development swift-Properties and methods

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.