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 }

 

相關文章

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.