Swift Learning notes sixth (class, properties, methods)

Source: Internet
Author: User
Tags class definition constant constructor instance method reset
class definition

We represent classes and structs by keyword class and struct, and define their specific contents in a pair of curly braces

/*
 class SomeClass {
 //class definition goes here
 }
 struct Somestructure {
 //structure definition G OES here
 }
 */

Class and struct common
/*
1. Defining properties for storing values
2. Define methods to provide functionality
3. Define satellite scripts for accessing values
4. Define the constructor used to generate the initialization value
5. Expand to add the default implementation functionality
6. Compliance with the Agreement to provide standard functionality for a class
*/

/*
Class and struct common
1. Inheritance allows one class to inherit the characteristics of another class
2. Type conversion allows you to check and interpret the type of a class instance at run time
3. The destructor allows an instance of a class to release any resources it has allocated
4. Reference counting allows multiple references to a class
*/

struct Area {
    var width = 0
    var height = 0
}

class jackmodel{
    var area = area ()
    var isfemale = False
    var name:string?
}


Let Somearea = Area () let
Somejackmodel = Jackmodel ()

print ("The width of area is \ (somearea.width)")
some JackModel.area.width = 1040
Print ("The width of area is \ (someJackModel.area.width)")

Note: Unlike the Objective-c language, Swift allows you to set the child properties of a struct property directly. The last example above, is directly set the resolution property in Somevideomode, the width of this sub-property, the above operation does not need to reset the resolution property

struct type member-by-constructor class there is no such construct-by-
hehe = Area (width:100,height:200)
print (hehe.height)

/*
1. struct and enum-value types are assigned to a variable, and the constant or itself is passed to a function when it is actually manipulated by its copy.
2. Class —————— > Unlike value types, reference types are referenced when assigned to a variable, constant, or passed to a function, and are not copies. Therefore, referring to an existing instance itself instead of its copy
*/ identity operator

Determine whether two classes are exactly equal
Identity operator
/*
Because a class is a reference type, there may be multiple constants and variables that reference a class instance at the same time in the background. (
This is not true for structs and enumerations. Because they are value types, their values are always copied when assigned to a constant, variable, or passed to a function.
1. Note that "equivalent to" (denoted by three equals, = = =) differs from "equals" (denoted by two equals, = =)
2. "Equivalent to" a constant or variable that represents a two class type (class type) refers to the same class instance.
3. "Equals" means two instances of the value "equal" or "Same"
* * selection of classes and structures

/*
However, struct instances are always passed by value, and class instances are always passed by reference.
This means that the two apply different tasks. When you consider the construction and function of a project's data, you need to decide whether each data construct is defined as a class or struct.
1. The main purpose of the structure is to encapsulate a small number of related simple data values.
2. It is reasonable to expect that when an instance of a struct is assigned or passed, the encapsulated data will be copied instead of referenced.
3. Any value type attribute stored in the struct will also be copied, not referenced.
4. Structs do not need to inherit another property or behavior of an existing type.
5. In practice, this means that the vast majority of custom data constructs should be classes, not structs.
* /value Pass and value copy

/*
The string, array, and dictionary (Dictionary) types in Swift are implemented in the form of structs.
This means that when the String,array,dictionary type data is assigned to a new constant (or variable), or is passed into a function (or method), their value is copied (the value is passed
The objective-c string (nsstring), Array (Nsarray), and Dictionary (nsdictionary) types are implemented in the form of classes, which are different from the values passed in Swfit. Nsstring,nsarray,nsdictionary No value copy occurs when an assignment is made or passed into a function (or method), but rather a reference to an existing instance.
*/ Property

/*
Simply put, a stored property is a constant or variable stored in an instance of a particular class or struct.
The storage property can be a variable store property (defined with the keyword VAR) or a constant storage attribute (defined with the keyword let)
*/

Main introduction under deferred storage properties lazy keyword
/*
1. Can be understood as lazy loading, here are keywords to the attribute assist
2. The deferred storage attribute must be declared as a variable (using the var keyword), because the value of the property may not be available until the instance construction is complete. The constant property must have an initial value before the construction process is complete, and therefore cannot be declared as a deferred attribute.
*/

Class Dataimporter {/
    *
     Dataimporter are classes that import data from external files.
     initialization of this class can take a lot of time.
     so it's not necessary to initialize in the first place
     . * *
    var fileName = "Data.txt"
}

class DataManager {
    lazy var Importer = Dataimporter ()
    var data = String ()
    //This is a data management function
} let

manager = DataManager ()
Manager.data.append ("mikejing")
manager.data.append ("!!!")
the Importer property of the print (Manager.data)//Dataimporter instance has not been created
print (manager.importer.fileName)
// The importer property of the Dataimporter instance is now created
//output "Data.txt"
Getter Setter Didset Willset method
Getter Setter Willset Didset
class Stepcounter {
    var totalsteps:int = 0 {

//        get {
//            return T Otalsteps
//        }
//        set {
//            totalsteps = newvalue
//        }
        //called before setter method is set
        Willset (newtotalsteps) {
            print ("will set \ (Newtotalsteps)
        }}
        //Assign value when
        didset {
            Print ("did set")
            if totalsteps > OldValue  {
                print ("Add \ (totalsteps-oldvalue) steps")
            }
        }}} let

name = Stepcounter () Name.totalsteps = +//would set//did
set
//Add Steps
name.totalsteps = 540
* * would
 set 540 did
 set
 add steps
 *
/ Name.totalsteps = 775/
* would
 set 775 did
 set
 add 235 steps
 */


Func Method

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).

Class Counter {
    var count = 0
    func increment () {
        count + = 1
    }
    //By is an external parameter  amount is the internal parameter
    Func Inc Rement (by Amount:int) {
        count + = Amount
    }
    func reset () {
        count = 0
    }} let
counter = Coun ter ()
//The initial counter value is 0
counter.increment ()
//The counter ' s value was now 1
counter.in Crement (By:5)
//The counter ' s value is now 6
counter.reset ()
//The counter ' s value was now 0
Modify the property of a value type in an instance method mutating

/* 1. Modify value types in the sample method modifying value Types from within Instance Methods
* 2. Structs and enumerations are value types. In general, a property of a value type cannot be modified in its instance method.
* 3.mutating method can change its properties from inside the method
*/

Method One modifies the originally created type variable
struct point{
    var x = 0.0
    var y = 0.0
    mutating func movepoint (x deltax:double,y deltay: Double) {
        x + = DeltaX
        y + = DeltaY
    }
}

var pointa = point (x:1.0,y:1.0)
print ("x=\ (pointa.x), y=\ (POINTA.Y) ")
Pointa.movepoint (X:9, Y:9)
print (" x=\ (pointa.x), y=\ (POINTA.Y) ")

Note: You cannot call a mutation method on a struct type constant, because a constant property cannot be changed, even if you want to change the variable property of a constant.

Method Two: Another method of substitution self the  newly created object will replace the previous value

struct pointb{
    var x1 = 0.0
    var y1 = 0.0
    mutating func move POINTB (x deltax:double,y deltay:double) {Self
        = POINTB (x1:x1 + deltax,y1:y1+deltay)
    }
}

var POINTB = POINTB (x1:200,y1:200)
print ("x=\ (pointb.x1), y=\ (pointb.y1)")
Pointb.movepointb (X:9, Y:9)
Print ("x=\ (pointb.x1), y=\ (pointb.y1)")



Note Address

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.