最初のswiftプログラム:計算機、100行のコードに及ばないで、簡単でしょう!
2517 ワード
どれだけ簡単かどれだけ簡単かは、100行のコード未満で計算機を実現します.
//
// ViewController.swift
// Calculator
//
// Created by purkylin on 14-6-19.
// Copyright (c) 2014 Purkylin. All rights reserved.
//
import UIKit
extension String
{
// subscript operator override
subscript(index:Int) -> Character?
{
var cur = 0
for c in self {
if cur == index {
return c
}
}
// return nil
let ret:Character?
return ret
}
}
class ViewController: UIViewController {
var operand1: Int = 0; // left operand
var operand2: Int = 0; // right operand
var operator: Character = "#"; // operator:+-*/=
@IBOutlet var resultLabel : UILabel = nil // output result
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
@IBAction func onClick(sender : UIButton) {
println("Click" + sender.titleForState(UIControlState.Normal));
var label = sender.titleForState(UIControlState.Normal);
var c:Character = label[0]!
switch c{
case "+","-","*","/":
operator = c
case "=":
var result = 0
switch operator {
case "+":
result = operand1 + operand2
case "-":
result = operand1 - operand2
case "*":
result = operand1 * operand2
case "/":
result = operand1 / operand2
default:
break
}
resultLabel.text = "\(result)"
// clear status
operator = "#"
operand1 = result
operand2 = 0
break
default:
if operator=="#" {
let tmp = label.toInt()!
operand1 = operand1*10 + tmp
resultLabel.text = "\(operand1)"
}
else {
let tmp = label.toInt()!
operand2 = operand2*10 + tmp
resultLabel.text = "\(operand2)"
}
}
}
// ACTION , ONCLICK
@IBAction func clearClick(sender : UIButton) {
operand1 = 0
operand2 = 0
operator = "#"
resultLabel.text = "0"
}
}