手把手帶你學(xué)習(xí)Swift3.0(21):類的屬性

//: Playground - noun: a place where people can play

import UIKit

// 1.創(chuàng)建類
class Student {
    // 類的屬性定義
    // 存儲屬性: 用于存儲實(shí)例的常量&變量
    var name : String = ""
    var age : Int = 0
    var mathScore : Double = 0.0
    var chineseScore : Double = 0.0
    
    // 計(jì)算屬性: 通過某種方式計(jì)算得來結(jié)果的屬性,就是計(jì)算屬性 --> 只讀屬性(了解)
    var averageScore : Double {
        return (chineseScore + mathScore) * 0.5
    }
    
    // 類屬性: 和整個類相關(guān)的屬性, 并且是通過類名進(jìn)行訪問
    static var courseCount : Int = 0
    
    
    // 給類擴(kuò)充函數(shù)
    // 在OC中寫的很多沒有參數(shù)的方法, 在swift中可以寫成計(jì)算屬性
    /*
    func getAverageScore() -> Double {
        return (chineseScore + mathScore) * 0.5
    }
    */
}

// 2.創(chuàng)建類的對象
let stu = Student()

stu.name = "why"
stu.age = 18
stu.mathScore = 90
stu.chineseScore = 60
print(stu.name, stu.age)

// 3.需求: 獲取某一個學(xué)生的平均成績
// let averageScore = (stu.mathScore + stu.chineseScore) * 0.5
// print(stu.getAverageScore())
print(stu.averageScore)

// 4.訪問類屬性
// stu.cour
Student.courseCount = 2
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容