Swift儲存屬性

來源:互聯網
上載者:User
////  main.swift//  Swift儲存屬性////  Created by Goddog on 15/7/19.//  Copyright © 2015年 Goddog. All rights reserved.//import Foundationprint("儲存屬性是指儲存在類、結構體裡的變數或常量,可分為執行個體儲存屬性和類型儲存屬性,執行個體儲存屬性屬於單個執行個體,類型儲存屬性屬於類型本身")print("枚舉不能定義執行個體儲存屬性,只有類和結構體才能定義執行個體儲存屬性;")print("上一節中結構體Size可以不指定初始值但是要聲明為可選類型")struct Size {    var width: Int!    var height: Int!}var s1 = Size()var s2 = Size(width: 10, height: 20)//MARK: - 執行個體儲存屬性與執行個體變數//執行個體儲存屬性用於儲存該類型的執行個體的狀態資料struct FixedLength{    var start: Int    let length: Int    //定義常量儲存屬性,可以不指定初始值} var rg = FixedLength(start: 2, length: 8)print("開始:\(rg.start), 長度:\(rg.length)")rg.start = 1   //變數可以重新賦值//rg.length = 10  //常量不可重新賦值//MARK: - 結構體常量與執行個體屬性struct Range{    //定義兩個變數儲存屬性    var start: Int    var length: Int}let rge = Range(start: 1, length: 2)print("起點:\(rge.start), 終點:\(rge.length)")//rge.start = 3          //用let聲明的rge執行個體是不可變的//rge.length = 4//MARK: - 延遲儲存屬性//延遲儲存屬性指的是第一次被調用時候才會被計算初始值的屬性,用lazy修飾符class Dept{    var id: Int    var info: String    init(id: Int)    {        self.id = id        //暫停2s        NSThread.sleepForTimeInterval(2)        self.info = "讀取資料庫"    }}class User {    var id: Int = 0    lazy var dept = Dept(id: 10)  //消極式載入機制    var nicks = [String]()   //數組}//建立user執行個體var user = User()user.nicks.append("曹操")user.nicks.append("劉備")user.nicks.append("孫權")print(user.nicks)

相關文章

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.