Swift学习笔记(二):属性、元组

一、属性的getter和setter

//设置计算型属性:其并不真正的存储值,而是每次通过其他值计算得来
var subtotal: Double {
  //getter:通过total、taxPct计算获得total的值  
  get {
    return total / (taxPct + 1)
  }
  //setter:更新的是相关的值(比如此处基于newSubtotal来设置total、taxPct的值)
  set(newSubtotal) { 
     //... 
  }
}

二、元组 | Tuples

//创建一个unamed tuples
let tipAndTotal = (4.00, 25.19)
//创建一个named tuples
let tipAndTotalNamed = (tipAmt:4.00, total:25.19)
tipAndTotalNamed.tipAmt
tipAndTotalNamed.total
//单行创建tuples
let tipAndTotalNamed:(tipAmt:Double, total:Double) = (4.00, 25.19)

  返回元组类型

let total = 21.19
let taxPct = 0.06
let subtotal = total / (taxPct + 1)
//这里返回的是元组的类型
func calcTipWithTipPct(tipPct:Double) -> (tipAmt:Double, total:Double) {
  let tipAmt = subtotal * tipPct
  let finalTotal = total + tipAmt
  return (tipAmt, finalTotal)
}
calcTipWithTipPct(0.20)

三、

posted @ 2014-07-19 14:14  Evan_You  阅读(303)  评论(0编辑  收藏  举报