Swift斯坦福公開課(1-3)代碼中文注釋

//
//  ViewController.swift
//  calculator
//
//  Created by 郭百度 on 2017/9/23.
//  Copyright ? 2017年 Luke. All rights reserved.
//

import UIKit

class ViewController: UIViewController {
    @IBOutlet weak var display: UILabel!
    var userIsInTheMiddleOfTyping = false
    var lessOnePoint = true
    @IBAction func touchDigit(_ sender: UIButton) {
        let digit = sender.currentTitle!
        //課后修正計算器bug添加,當輸入為"."時判斷,屏幕上數字是否已有小數點,是的話不執行
        let point: Character = "."
        if digit == String(point) && display.text!.contains(".") {
                lessOnePoint = false
        }
        if lessOnePoint {
            if userIsInTheMiddleOfTyping {
                let textCurrentlyInDisplay = display.text!
                display.text = textCurrentlyInDisplay + digit
                print("I'm \(digit) b")
            } else {
                display.text = digit
                userIsInTheMiddleOfTyping = true
                print("I'm \(digit) c")
            }
        }
        lessOnePoint = true
    }
    
    var displayVaule: Double {
        get {
            return Double(display.text!)!
        }
        set {
            display.text = String(newValue)
        }
    }

    private var  brain = CalculatorBrain()
    
    @IBAction func performOperation(_ sender: UIButton) {
        //執行運算按鈕中,如果用戶正在鍵入中,那么將display值提交到brain的蓄存器中,用于實現當用戶點擊開根號等計算時,將屏幕display數進行緩存
        if userIsInTheMiddleOfTyping {
            brain.setOperand(displayVaule)
        }
        //標識用戶停止鍵入
        userIsInTheMiddleOfTyping = false
        //那么讓model執行數學運算符判斷,將輸入值sender標題→mathmaticalSymbol數學符號→brain執行運算函數
        if let mathmaticalSymbol = sender.currentTitle {
            brain.performOperation(mathmaticalSymbol)
        }
        //那么讓我們將model中的結果從堆中復制給view中result,在view中將其復制給屏幕(label)
        if let result = brain.result {
            displayVaule = result
        }
    }
}
//
//  CalculatorBrain.swift
//  calculator
//
//  Created by 郭百度 on 2017/9/23.
//  Copyright ? 2017年 Luke. All rights reserved.
//

import Foundation
//func changeSign(operand: Double) -> Double {
//    return -operand
//}
//func multiply(op1:Double, op2:Double) -> Double{
//    return op1 * op2
//}


struct CalculatorBrain {
    //構建私有變量accumulator雙精度蓄存器
    private var accumulator: Double?
    
    private enum Operation {
        case constant(Double)
        case unaryOperation((Double) -> Double)
        case binaryOperation((Double,Double) -> Double)
        case equals
    }
    
    //生命私有變量operations(加了s)為字典,為字典賦值
    private var operations: Dictionary<String,Operation> = [
        "π" : Operation.constant(Double.pi),
        "e" : Operation.constant(M_E),//M_E,
        "√" : Operation.unaryOperation(sqrt),//sqrt,
        "cos" : Operation.unaryOperation(cos), //cos
        "±" : Operation.unaryOperation({-$0}), //±
        "+" : Operation.binaryOperation({ $0 + $1} ), // x *
        "-" : Operation.binaryOperation({ $0 - $1 }), // x *
        "×" : Operation.binaryOperation({ $0 * $1 }), // x *
        "÷" : Operation.binaryOperation({ $0 / $1 }), // x *
        "=" : Operation.equals
    ]

    //構建多變函數執行運算,輸入值忽略標簽,變量symbol符號,類型為字符串
    mutating func performOperation(_ symbol: String) {
        //如果字典查詢operations[symbol]有值的話,將其賦值給變量operation,沒有則跳過整個枚舉
        if let operation = operations[symbol] {
            //對賦值后的operation進行解析
            switch operation {
                //聲明字典內提取為“值”value,將字典內常數值直接給蓄存器
                case .constant(let value):
                    accumulator = value
                //聲明字典內提取為“函數”function,蓄存器中若不為nil,則進行sqrt、cos等枚舉的函數運算,否則跳過
                case .unaryOperation(let function):
                    if accumulator != nil {
                        accumulator = function(accumulator!)
                    }
                //聲明字典內提取為“二元函數運算”同樣適用function(不同枚舉不沖突),蓄存器中若不為nil,則進行枚舉binaryOperation字典中的運算公式,運算函數為function,為區別,此處與官方教程不同使用了function2和functionVaule更易懂
                case .binaryOperation(let functionVaule):
                    if accumulator != nil {
                        pendingBinaryOperation = PendingBinaryOperation(funciton2: functionVaule, firstOperand: accumulator!)
                        accumulator = nil
                    }
                case .equals:
                    performPendingBinaryOperation()
            }
        } else {
            //之前一個用x當乘號一個用×當乘號……然后乘法一直沒用……坑
            print("沒有找到枚舉值")
        }
    }
    
    private mutating func performPendingBinaryOperation() {
        if pendingBinaryOperation != nil && accumulator != nil {
            accumulator = pendingBinaryOperation!.perform(with: accumulator!)
            pendingBinaryOperation = nil
        }
    }
    
    private var pendingBinaryOperation: PendingBinaryOperation?
    private struct PendingBinaryOperation {
        //此處聲明了二元函數運算中為兩個雙精度變量輸入及一個雙精度變量輸出
        let funciton2 : (Double,Double) -> Double
        let firstOperand : Double
        
        func perform(with secondOperand:Double) -> Double {
            //此處調用了function為枚舉計算公式,在swift中使用$0、$1...按順序輸入變量
            return funciton2(firstOperand,secondOperand)
        }
    }
    
    mutating func setOperand(_ operand:Double) {
        accumulator = operand
    }
    //輸出結果
    var result: Double? {
        get {
            return accumulator
        }
    }
}

引用
Swift 語言 iOS10 開發 斯坦福(Stanford) CS193p 公開課(1)
Swift 語言 iOS10 開發 斯坦福(Stanford) CS193p 公開課(2)
Swift 語言 iOS10 開發 斯坦福(Stanford) CS193p 公開課(3)

最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。
  • 序言:七十年代末,一起剝皮案震驚了整個濱河市,隨后出現的幾起案子,更是在濱河造成了極大的恐慌,老刑警劉巖,帶你破解...
    沈念sama閱讀 228,606評論 6 533
  • 序言:濱河連續發生了三起死亡事件,死亡現場離奇詭異,居然都是意外死亡,警方通過查閱死者的電腦和手機,發現死者居然都...
    沈念sama閱讀 98,582評論 3 418
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來,“玉大人,你說我怎么就攤上這事。” “怎么了?”我有些...
    開封第一講書人閱讀 176,540評論 0 376
  • 文/不壞的土叔 我叫張陵,是天一觀的道長。 經常有香客問我,道長,這世上最難降的妖魔是什么? 我笑而不...
    開封第一講書人閱讀 63,028評論 1 314
  • 正文 為了忘掉前任,我火速辦了婚禮,結果婚禮上,老公的妹妹穿的比我還像新娘。我一直安慰自己,他們只是感情好,可當我...
    茶點故事閱讀 71,801評論 6 410
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著,像睡著了一般。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發上,一...
    開封第一講書人閱讀 55,223評論 1 324
  • 那天,我揣著相機與錄音,去河邊找鬼。 笑死,一個胖子當著我的面吹牛,可吹牛的內容都是我干的。 我是一名探鬼主播,決...
    沈念sama閱讀 43,294評論 3 442
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼!你這毒婦竟也來了?” 一聲冷哼從身側響起,我...
    開封第一講書人閱讀 42,442評論 0 289
  • 序言:老撾萬榮一對情侶失蹤,失蹤者是張志新(化名)和其女友劉穎,沒想到半個月后,有當地人在樹林里發現了一具尸體,經...
    沈念sama閱讀 48,976評論 1 335
  • 正文 獨居荒郊野嶺守林人離奇死亡,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內容為張勛視角 年9月15日...
    茶點故事閱讀 40,800評論 3 354
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發現自己被綠了。 大學時的朋友給我發了我未婚夫和他白月光在一起吃飯的照片。...
    茶點故事閱讀 42,996評論 1 369
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖,靈堂內的尸體忽然破棺而出,到底是詐尸還是另有隱情,我是刑警寧澤,帶...
    沈念sama閱讀 38,543評論 5 360
  • 正文 年R本政府宣布,位于F島的核電站,受9級特大地震影響,放射性物質發生泄漏。R本人自食惡果不足惜,卻給世界環境...
    茶點故事閱讀 44,233評論 3 347
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望。 院中可真熱鬧,春花似錦、人聲如沸。這莊子的主人今日做“春日...
    開封第一講書人閱讀 34,662評論 0 26
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽。三九已至,卻和暖如春,著一層夾襖步出監牢的瞬間,已是汗流浹背。 一陣腳步聲響...
    開封第一講書人閱讀 35,926評論 1 286
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留,地道東北人。 一個月前我還...
    沈念sama閱讀 51,702評論 3 392
  • 正文 我出身青樓,卻偏偏與公主長得像,于是被迫代替她去往敵國和親。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當晚...
    茶點故事閱讀 47,991評論 2 374

推薦閱讀更多精彩內容

  • 轉載自:https://github.com/Tim9Liu9/TimLiu-iOS[https://github...
    香橙柚子閱讀 8,647評論 0 36
  • 許久沒有聯系,你突然傳來簡訊,一張風景照,你說你在沐浴陽光。我便知道你想我了。此時我只需駕車去找你。我說可以等我嗎...
    忘年緘默閱讀 217評論 0 0
  • 木神山,在那遠古時期,這里盤踞著一個即便是放眼那塊大千世界中最龐大的大陸之中,都能夠算做是一方霸主的強大勢力,而那...
    混沌天書閱讀 339評論 0 0
  • 在我們的日常工作中,每天上下班都應該交接班, 每次只有交接到位了,接你班的同事才能順利的完成接下來的工作! 就拿我...
    Lzr_2017閱讀 141評論 0 4
  • 今天是圣誕節,但是依舊有很多人還是需要加班,還是需要學習,需要為自己的生活奮斗。資本主義的蜜糖明顯還是有很大成分的...
    Heaven綠閱讀 824評論 2 22