swift-storage properties, computed properties, class properties

Source: Internet
Author: User


// Class attribute definition

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 a method that can return the average score (note: swift is not recommended to use this way, a calculated attribute should be defined)
    func getAverageScore ()-> Double {
// If you use a certain property of the current object in swift, or call a method of the current object, you can use it directly without adding self
        return (mathScore chineseScore) * 0.5
    }
    
// Define the calculated attribute: the attribute whose result is calculated in another way is called the calculated attribute
// A lot of calculated attributes
    var averageScore: Double {
        return (mathScore chineseScore) * 0.5
    }
    
// Define class attributes: Class attributes are attributes related to the entire class, and are accessed directly through the class name
// Generally used for more points in simple interest
    static var courceCount: Int = 0
    
}

// Assign values to object properties
let stu = Student ()
stu.age = 10
stu.name = "wj"

stu.mathScore = 78
stu.chineseScore = 70

print (stu.age)

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

let averageScore = (stu.mathScore stu.chineseScore) * 0.5

let ave = stu.averageScore

// Class attributes
// Assign values to class attributes
Student.courceCount = 2 





swift-storage properties, computed properties, class properties


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.