Swift學習筆記(一):基礎

來源:互聯網
上載者:User

標籤:style   blog   color   使用   os   io   

一、常量 & 變數

//常量let constantsTeam = 1//變數var variablesTeam = 2

  儘可能使用常量,這樣更清晰並且記憶體更不容易腎虧。

二、顯示/隱式指定類型

//隱式let inferredTeam = 3//顯式let explicitTeam:Int = 4

三、字串輸出

//通過\(變數或常量名)來引用組合字元串println("\(inferredTeam) is bigger than \(variablesTeam)!")

四、類和方法

// 類使用class關鍵字聲明class TipCalculator {   // 在類中建立屬性  let total: Double  let taxPct: Double  let subtotal: Double   // 屬性必須在聲明時賦予一個初始值,或者在initializer裡,否則必須聲明其為optional(這裡使用的是initializer)  init(total:Double, taxPct:Double) {    self.total = total    self.taxPct = taxPct    subtotal = total / (taxPct + 1)  }   // 方法使用func關鍵字聲明,返回Double類型  func calcTipWithTipPct(tipPct:Double) -> Double {    return subtotal * tipPct  }   // 無傳回值方法  func printPossibleTips() {    println("15%: \(calcTipWithTipPct(0.15))")    println("18%: \(calcTipWithTipPct(0.18))")    println("20%: \(calcTipWithTipPct(0.20))")  } } // 建立類執行個體對象,通過類執行個體對象調用類中的方法let tipCalc = TipCalculator(total: 33.25, taxPct: 0.06)tipCalc.printPossibleTips()

五、數組和迴圈

//1let possibleTipsInferred = [0.15, 0.18, 0.20]let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20]//2for possibleTip in possibleTipsInferred {  println("\(possibleTip*100)%: \(calcTipWithTipPct(possibleTip))")}//3for i in 0..<possibleTipsInferred.count {  let possibleTip = possibleTipsInferred[i]  println("\(possibleTip*100)%: \(calcTipWithTipPct(possibleTip))")}

六、字典Dictionary

// 1func returnPossibleTips() -> [Int: Double] {   let possibleTipsInferred = [0.15, 0.18, 0.20]  let possibleTipsExplicit:[Double] = [0.15, 0.18, 0.20]   // 建立一個空字典  var retval = Dictionary<Int, Double>()  for possibleTip in possibleTipsInferred {    let intPct = Int(possibleTip*100)    // 賦值給字典    retval[intPct] = calcTipWithTipPct(possibleTip)  }  return retval }

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

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.