lol play

書評や技術ネタ及びイラストについての発信

Swift電卓


今日はすることがなかったので、swiftを使って電卓みたいなものを作りました(´・ω・`)

//
//  main.swift
//  calc
//
//  Created by RockBooker on 6/3/16.
//  Copyright © 2016 RockBooker. All rights reserved.
//

import Foundation

enum Result {
    case Success(Int)
    case Error(String)
}

let operators: Dictionary<String, (Int, Int) -> Int> = [
    // 添字の指定に応じて、関数を設定する
    "+": {n, m -> Int in n + m},
    "-": {n, m -> Int in n - m},
    "*": {n, m -> Int in n * m},
    "/": {n, m -> Int in n / m},
]

let usage = "USAGE: calc {num} {+|-|*|/} {num}"

func calc(op1: Int?, _ op2: Int?, with oprand: String) -> Result {
    if op1 != nil && op2 != nil {
        let n1 = op1!
        let n2 = op2!
        
        let calcFunction = operators[oprand]!
        let ans = calcFunction(n1, n2)
        
        return Result.Success(ans)
    } else {
        return Result.Error("Error!!")
    }
}


if Process.arguments.count != 4 {       // 引数の数には自身を含めることに注意する
    print(usage)
    exit(0)
}

let op1 = Int(Process.arguments[1])     // 左辺の数
let op2 = Int(Process.arguments[3])     // 右辺の数
let oprand = Process.arguments[2]       // 計算式

let result = calc(op1, op2, with: oprand)
switch result {
case let .Success(ans):
    print("ANSWER: ", ans)
case let .Error(msg):
    print("ERROR: ", msg)
}

swiftは見通し良く書けるので気に入っています。