Skip to content

Instantly share code, notes, and snippets.

@NeilsUltimateLab
Created June 3, 2018 12:16
Show Gist options
  • Save NeilsUltimateLab/cacec8a77a7ce90fda85471fad0ffadf to your computer and use it in GitHub Desktop.
Save NeilsUltimateLab/cacec8a77a7ce90fda85471fad0ffadf to your computer and use it in GitHub Desktop.
Simple Command Line Calculator
//
// main.swift
// Calculator
//
// Created by NeilsUltimateLab on 03/06/18.
// Copyright © 2018 NeilsUltimateLab. All rights reserved.
//
import Foundation
enum Token {
case sqrt(Float)
case sum(Float, Float)
case minus(Float, Float)
case multi(Float, Float)
case div(Float, Float)
private enum Command: String {
case sqrt
case sum
case minus
case multi
case div
}
init?(rawValue: Array<String>) {
guard !rawValue.isEmpty else { return nil }
if let command = Command(rawValue: rawValue[0]) {
switch command {
case .sqrt:
guard let value = Float(rawValue[1]) else { return nil }
self = .sqrt(value)
case .sum:
guard let val1 = Float(rawValue[1]), let val2 = Float(rawValue[2]) else { return nil }
self = .sum(val1, val2)
case .minus:
guard let val1 = Float(rawValue[1]), let val2 = Float(rawValue[2]) else { return nil }
self = .minus(val1, val2)
case .multi:
guard let val1 = Float(rawValue[1]), let val2 = Float(rawValue[2]) else { return nil }
self = .multi(val1, val2)
case .div:
guard let val1 = Float(rawValue[1]), let val2 = Float(rawValue[2]) else { return nil }
self = .div(val1, val2)
}
return
}
return nil
}
}
func compute(for token: Token) {
switch token {
case .sqrt(let val):
print("\nThe square root is: ", sqrt(Double(val)), "\n")
case .sum(let val1, let val2):
print("\nThe addition result is: ", val1 + val2, "\n")
case let .minus(val1, val2):
print("\nThe negation result is: ", val1 + val2, "\n")
case let .div(val1, val2):
guard val2 > 0 else {
print("\nWow you got an \"Infinity\"\n")
return
}
print("\nThe division result is: ", val1/val2, "\n")
case let .multi(val1, val2):
print("\nThe multiplication result is: ", val1 * val2, "\n")
}
}
func parse(input: Array<String>) {
if let token = Token(rawValue: input) {
compute(for: token)
}
}
func main() {
let argumanets = CommandLine.arguments.dropFirst()
parse(input: Array(argumanets))
}
main()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment