CS193P 2. More Xcode and Swift, MVC

继续 DEMO: Calculator

Swift 能类型推断

自动布局:

  • Pin: Spacing to nearest neighbor, Equal Widths, Equal Heights
  • Resolve Auto Layout Issues: Clear Constraints

87果然是个神奇的数字,我之前没有对齐就开始 Pin,始终无法得到“Add 87 Constraints”,自然没有得到自动对齐的理想布局。

代码如下:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
//
// ViewController.swift
// Calculator
//
// Created by Will Ge on 6/28/15.
// Copyright © 2015 gewill.org. All rights reserved.
//

import UIKit

class ViewController: UIViewController {


@IBOutlet weak var display: UILabel!

var userIsInTheMiddleOfTypingANumber: Bool = false

@IBAction func appendDigit(sender: UIButton) {
let digit = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber{
display.text = display.text! + digit
} else {
display.text = digit
userIsInTheMiddleOfTypingANumber = true
}

print("digit = \(digit)")
}

var operandStack = Array<Double>()

@IBAction func enter() {
userIsInTheMiddleOfTypingANumber = false
operandStack.append(displayValue)
print("operandStack = \(operandStack)")

}

@IBAction func operate(sender: UIButton) {
let operation = sender.currentTitle!
if userIsInTheMiddleOfTypingANumber {
enter()
}
switch operation {
case "×": performOperation { $0 * $1 }
case "÷": performOperation { $1 / $1 }
case "+": performOperation { $0 + $1 }
case "−": performOperation { $1 - $0 }
case "√": performOperation1 { sqrt($0) }
default: break
}
}

func performOperation(operation: (Double, Double) ->Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast(), operandStack.removeLast())
enter()
}
}

func performOperation1(operation: Double ->Double) {
if operandStack.count >= 2 {
displayValue = operation(operandStack.removeLast())
enter()
}
}


var displayValue: Double{
get {
return NSNumberFormatter().numberFromString(display.text!)!.doubleValue
}
set {
display.text = "\(newValue)"
userIsInTheMiddleOfTypingANumber = false
}
}
}

MVC:

  • 各个模块之间的含义
  • 模块之间的通信有无
  • 模块之间的控制关系

MVC