Swift物件導向中類和對象的屬性

來源:互聯網
上載者:User

標籤:ios   swift   

Swift中類和對象的屬性分為三種:儲存屬性,計算屬性和類屬性。

import Foundationclass Person {  // 儲存屬性必須賦初值  var score1: Int = 20  var score2: Int = 50  // 延遲儲存屬性,需要時再去分配  lazy var dog: Dog = Dog()  // 計算屬性,不能賦初值,提供get和set方法,  var sum: Int {    get {      return score1 + score2    }  }  // 類屬性,只能是計算屬性,使用類而非對象去調用  // 如 Person.desc  class var desc: String {    get {      return "This is one person."    }  }  // 構造方法  init() {    println("This is one person.")  }}class Dog {  init() {    println("This is one dog.")  }}var p = Person()println(Person.desc)println(p.score1)println(p.score2)println(p.sum)println(p.dog)

著作權聲明:本文為博主原創文章,未經博主允許不得轉載。

Swift物件導向中類和對象的屬性

相關文章

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.