Swift Learning Day 12th: Property definitions for classes

Source: Internet
Author: User
Tags custom name

label:

Class attribute introduction
There are many properties of classes in Swift
Storage properties: constants and variables that store instances
Calculated attributes: attributes calculated in some way
Class attributes: attributes related to the entire class itself
Storage attributes
The storage attribute is the simplest attribute, which is used as a part of the class instance to store constants and variables
You can provide a default value for the storage property, you can also initialize it in the initialization method, and must have a default value, otherwise it will report an error
The following is how to store attributes
Both age and name are storage attributes used to record the age and name of the student
chineseScore and mathScore are also storage attributes used to record the student's Chinese score and math score
class Student: NSObject {
    // Define attributes
    // storage attributes
    var age: Int = 0
    var name: String?

    var chineseScore: Double = 0.0
    var mathScore: Double = 0.0
}

// Create student object
let stu = Student ()

// Assign values to storage attributes
stu.age = 10
stu.name = "why"

stu.chineseScore = 89.0
stu.mathScore = 98.0
Calculated attribute
The calculated attribute does not store the actual value, but provides a getter and an optional setter to indirectly get and set other attributes
Calculated attributes generally only provide getter methods
If only the getter is provided, and the setter is not provided, the calculated attribute is read-only and the get {} can be omitted
Here is how to calculate attributes
averageScore is a calculated attribute, which is calculated through chineseScore and mathScore
There is a newValue variable in the setter method, which is assigned by the system.
class Student: NSObject {
    // Define attributes
    // storage attributes
    var age: Int = 0
    var name: String?

    var chineseScore: Double = 0.0
    var mathScore: Double = 0.0

    // calculated attribute
    var averageScore: Double {
        get {
            return (chineseScore + mathScore) / 2
        }

        // makes no sense, because the value is still calculated when the value is obtained later
        // newValue is the variable name assigned by the system, and the new value is stored internally
        set {
            self.averageScore = newValue
        }
    }
}

// Get the value of the calculated attribute
print (stu.averageScore)
Class attribute
Class attributes are associated with the class, not with instances of the class
All classes and instances share a class attribute. So after a certain modification, the class attribute will be modified
The setting and modification of class attributes need to be done through the class
The following is how to write class attributes
Class attributes are decorated with static
courseCount is a class attribute used to record how many courses a student has
class Student: NSObject {
    // Define attributes
    // storage attributes
    var age: Int = 0
    var name: String?

    var chineseScore: Double = 0.0
    var mathScore: Double = 0.0

    // calculated attribute
    var averageScore: Double {
        get {
            return (chineseScore + mathScore) / 2
        }

        // meaningless. NewValue is the variable name assigned by the system, which stores the new value internally
        set {
            self.averageScore = newValue
        }
    }

    // class attribute
    static var corseCount: Int = 0
}

// Set the value of the class attribute
Student.corseCount = 3
// Get the value of the class attribute
print (Student.corseCount)
Listen for changes in attributes
In OC, we can rewrite the set method to monitor the property changes
Swift can monitor and respond to changes in attribute values through attribute observers
It is usually to monitor changes in storage properties and class properties. (For calculated properties, we do not need to define property observers, because we can directly observe and respond to changes in this value in the calculated property setter)
We define the observer by setting the following observation method
willSet: Set before the attribute value is stored. At this time, the new attribute value is passed in as a constant parameter. The parameter name defaults to newValue, we can define the parameter name ourselves
didSet: Called immediately after the new attribute value is stored. Same as willSet, the old value of the property is passed in at this time, the default parameter name is oldValue
willSet and didSet will only be called when the property is set for the first time, and these initialization methods will not be called during initialization
The monitoring method is as follows:
Monitor changes in age and name
class Person: NSObject {
    var name: String? {
        // You can give newValue a custom name
        willSet (new) {// The property will be changed
            // There is a default system property newValue in this method, used to store the new value
            print (name)
            print (new)
        }
        // You can give oldValue a custom name
        didSet (old) {// The property value has changed
            // There is a default system property oldValue in this method, used to store the old value
            print (name)
            print (old)
        }
    }
    var age: Int = 0
    var height: Double = 0.0
}

let p: Person = Person ()

// When assigning value, monitor the change of the attribute
// By overriding the set method in OC
// In swift, you can add listeners to properties
p.name = "why"

//p.name = "yz"


import UIKit

class Student: NSObject {
    // Define attributes
    // Define storage attributes
    var age: Int = 0
    var name: String?
    
    var mathScore: Double = 0.0
    var chineseScore: Double = 0.0
    
    // Define the calculated attribute: the attribute whose result is calculated by other means is called the calculated attribute
    var averageScore: Double {
        return (mathScore + chineseScore) * 0.5
    }
    
    // Define class attributes: Class attributes are attributes related to the entire class. They are accessed by class name
    static var courseCount: Int = 0
    
    / *
    // Define the method to return the average score
    func getAverageScore ()-> Double {
        // In Swift development, if you use a certain property of the current object, or call a certain method of the current object, you can use it directly, without adding self
        return (mathScore + chineseScore) * 0.5
    }
    * /
}

// Assign values to class attributes
Student.courseCount = 2

// create object
let stu = Student ()

// Assign values to the properties of the object
stu.age = 10
stu.name = "yz"
stu.mathScore = 78
stu.chineseScore = 59.9

print (stu.age)
if let name = stu.name {
    print (name)
}

let averageScore = stu.averageScore
 

swift learning twelfth day: class attribute definition

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.