1. 程式人生 > >swift - 基礎屬性 - 屬性寫法

swift - 基礎屬性 - 屬性寫法

over swift load() guard urn lse private har 賦值

    var num1 : Int = 0
    
    var num2 : Int = 5
    
    /// 1.計算屬性
    var num3 : Int{
        return num1 + num2
    }
    
    /// 2.閉包屬性
    private lazy var num4 : Int = {
       return num1 + num2
    }()
    
    override func viewDidLoad() {
        super.viewDidLoad()
        print(num3)
        print(num4)
    }

  

2.類屬性

class Student: NSObject {
    /// 類屬性
    static var score : Int = 0
}


    override func viewDidLoad() {
        super.viewDidLoad()

        Student.score = 1
        print(Student.score)
    }

  

3. 對象屬性賦值

class Student: NSObject {
    
    var age:Int = 0
    
    ///可選屬性: name1 和name2一個意思
    var name1:String?
    var name2:String? = nil
}


        let stu = Student()
        stu.age = 10
        stu.name1 = "1蛋"
        stu.name2 = "2蛋"
        print(stu.age)
        
        /// 可選屬性 解包寫法1
        if let name = stu.name1{
            print(name)
        }
        
        /// 可選屬性 解包寫法2
        guard let name2 = stu.name2 else { return }
        print(name2)

  

swift - 基礎屬性 - 屬性寫法