iT邦幫忙

2017 iT 邦幫忙鐵人賽
DAY 3
0
自我挑戰組

白鬍子老頭30天 Swift Ios系列 第 3

Day3 lecture 2 -2 計算機範例

這裡計算機範例套用了MVC
將計算放進了Model

Model:
//這裡用到enum 和 dictinary
這邊居然可以有參數

enum Operation {
Constant (Double)
Unary ((Double)-> Double)
Binary ((Double,Double) -> Double)
Equle
}

在Dictinarty輸入參數

var operation : Dictinary<string,Model.Operation> = [
"n":Operation.Constant (M_PI),
"e":Operation.Constant (M_E),
"開根號":Operation.Unary (sqrt),
"c":Operation.Unary (cos),
//這裡直接簡化了closure $0是參數1 $1是參數2
"x":Operation.Binary ($0*$1),
]

在performFunc 做出來

func performFunc (symbol : string){
//取出dic裡的值
    if let op = operation[symbol]{
        swich op{
               //這邊的變數就等於你在字典裡設進去的
            case .Constant(let value) : 計算的值 = value
               //甚至可以傳入function 回傳 Double 
            case .Unary(let func) : 計算得值 = func(accumator)
            
        }
    }
}

Computed propertie

除儲存屬性外,類別、結構和列舉可以定義計算屬性,計算屬性不直接儲存值,而是提供一個 getter 來獲取值,一個可選的 setter 來間接設置其他屬性或變數的值。

這裡用到使程式碼更簡潔

var displayValue :Double {
get {
return Double(display.text!)!
}
set {
display.text = newValue
}
}

接下來你只要

displayValue = XXXXX

closure sytax

Swift型別推斷 (Type Inference) + 閉包 (Closure) 兩個加在一起 boom 變超簡潔
原本的乘法寫法

func multiply (op1: Double, op2: Double) -> Double {
    return op1 * op2
}

operation 裡的 case

"x":Operation.Binary (multiply)

變成closure case

"x":Operation.Binary ({ (op1: Double, op2: Double) -> Double in
    return op1 * op2
})

這個大括號刮起來的就是closure multiplay就不需要了
因為我們已經定義他的參數型別了 所以 op1 op2 的 Double 可以拿掉
也定義他會回傳一個 Double 所以 return也可以拿掉
就會變成如下

"x":Operation.Binary ({(op1, op2)  in
     op1 * op2
})

再來 swift 允許不命名參數,預設名稱會是:$0, $1
沒有命名 in 也不需要了
所以就會變這樣

"x":Operation.Binary ($0*$1)

哇靠好短


上一篇
Day2 lecture 2 MVC
下一篇
Day4 lecture 3 Swift and Foundation Framework -1
系列文
白鬍子老頭30天 Swift Ios30
圖片
  直播研討會
圖片
{{ item.channelVendor }} {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言