首页 > 代码库 > Swift学习笔记(一):基础

Swift学习笔记(一):基础

一、常量 & 变量

//常量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 }