I have tried learning to develop for iOS for some time, and have gone though a number of books in my attempt to teach myself. While I was able to learn some of the basics of programming, mainly in Objective C, C++, and Python it was still far from being able to actually make a working program.

So currently I have a basic understanding of both the Objective C and C++ language, which is a good foundation to have, and now recently with Apple releasing the Swift programming language I am hoping I can make better progress. I feel as if things are starting to come together, with the help of a number of new training sources.

The first one I came across was Code with Chris. Chris shows you how to develop iOS applications with the Swift programming language in a way that is easy to understand and apply. He will take you step by step, explaining in simple terms what is needed. During the process you will also make a number of working applications. He provides assessments after each chapter to help ensure you are remembering the key factors from each lesson. There are also programming challenges where you can apply what you have learned to build upon your applications that you create. With the skills you learn you can also build further upon your base application to provide further features and enhance them even further. This method of you actually working with the code yourself, and thinking things through is one of the best learning methods available. To really learn to code, it is best to practice as much as possible, and also to start as soon as possible. Do not wait until you know it all before you start, just jump right in.

The latest training class I came across is from iTunes U with Stanford. This is a recent class that just began in January of 2015. The classes are video lectures with slides, and code examples. In this class the professor will show you how to use swift to create a calculator program. Once again he only shows the base of the program, and provides assignments to add further functionality to the program, such as the ability to calculate sin, cos, pi, enter a valid decimal number, and more.

I have found both courses very valuable to my iOS training and would recommend both to anyone wanting to learn Swift, especially if you have had issues in the past grasping the language.

Below is my current calculator code. If you are planing on doing the Stanford iTunes U course I would recommend not reading the code as it will spoil your learning efforts. It is better to work out these issues yourself. After much work, I myself have managed to get the majority of the program working the way it should, while the code may not be as efficient as it should, it does work.

I have two issues that I am still working on, and I feel this may take longer as I seem to be at a loss right now. The first is my function of Pi. It should work so that no matter the order you use it, it will calculate. For instance let’s stay I want to multiply 3 to π. I should be able to do this by entering: 3 ⏎ π ×, or 3 π ×, or π 3 ×. My code works to a point. The first two expressions work just fine, the last does not, and returns the result of 0.0.

My final issue to resolve is the history display. At the moment it just shows what is currently in the operandStack. What it needs to display is the full history of every operand and operation. This is taking more work than I though. I could be going in the wrong direction. I may need to create a new array for this feature instead of trying to use other portions of the existing code to achieve my results.

Finally I am trying to do the entire project with as few lines of code as possible. Later in the class I will be modifying the code to fit the MVC model format. The app is currently setup with auto layout and will work properly on any size iPhone of any orientation, as well as any iPad in any orientation. Speaking of auto layout, this was a difficult subject for me, and both classes mentioned above did a great job of teaching me how to properly use this feature.

As of today I had made a simple math program for kids, a word game which was based from a template, the game of war, this calculator program, and I am currently working a quiz program. If anyone has any suggestions for my calculator, please feel free to comment. I don’t need say the answer, however a hint or a suggestion in which direction to go might get me back on track.

Happy coding!

Update: I have resolved the issue I was having with Pi, and also converted the code to follow the MVC model format.  I am keeping all code updates on github.  I will make a follow up post in a week to talk about some of the new skills I have learned taking the course.

Below is the current code:

//
// ViewController.swift
// Calculator
//
// Created by Ivan Windon on 2/6/15.
// Copyright (c) 2015 Ivan Windon. All rights reserved.
//

import UIKit

class ViewController: UIViewController {

@IBOutlet weak var display: UILabel!
@IBOutlet weak var history: UILabel!

var userIsInTheMiddleOfTypingANumber = false
let x = M_PI

@IBAction func appendDigit(sender: UIButton) {

let digit = sender.currentTitle!

if userIsInTheMiddleOfTypingANumber {
     display.text = display.text! + digit
     } else {
          display.text = digit
          userIsInTheMiddleOfTypingANumber = true
     }
}

@IBAction func operate(sender: UIButton) {

let operation = sender.currentTitle!

switch operation {
     case "×": performOperation { $0 * $1 }
     case "÷": performOperation { $1 / $0 }
     case "+": performOperation { $0 + $1 }
     case "−": performOperation { $1 - $0 }
     case "√": performOperation { sqrt($0) }
     case "sin": performOperation { sin($0) }
     case "cos": performOperation { cos($0) }
     default: break
     }

}

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

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

}

var operandStack = Array()

@IBAction func enter() {
     userIsInTheMiddleOfTypingANumber = false
     decimalIsPressed = false
     operandStack.append(displayValue)
     history.text = "\(displayValue)"
     println("operandStack = \(operandStack)")

}
var decimalIsPressed = false

@IBAction func decimal() {
     userIsInTheMiddleOfTypingANumber = true
     if decimalIsPressed == false {
          display.text = display.text! + "."
          decimalIsPressed = true
     }
}

@IBAction func pi() {
     userIsInTheMiddleOfTypingANumber = true
     if display.text != "0" {
          enter()
          display.text = "\(x)"
          enter()
          } else {
               display.text = "\(x)"
               enter()
     }
}

@IBAction func clear() {
     userIsInTheMiddleOfTypingANumber = false
     operandStack.removeAll()
     display.text = "0"
     enter()
}

var displayValue: Double {
     get {
     return NSNumberFormatter().numberFromString(display.text!)!.doubleValue

     }
     set {
     display.text = "\(newValue)"
     userIsInTheMiddleOfTypingANumber = false
     }

   }

}

5 Responses to “Swift Calculator Program and learning to Code”

  1. Awesome work Ivan! Thanks for the mention and congratulations on all of the apps you’ve built in such a short time!

  2. Hi Ivan,

    I am trying to make the same program, but when I click on cos(anyNumber) it is giving a wrong result. have you ever faced any problem like that?
    ex: operandStack = [1.0] -> here i click on cos()
    operandStack = [0.54030230586814]

    the result must be: 0.9998476952

    • I actually get the same result, however I had not turned my attention to figuring out why as of yet. I ended up having to work on my CCNA Security studies for a while, along with finishing up the spring semester at Penn State. I’ll have more time for my programming efforts in a month and will be back at working actively on this program. If you find an answer, or a clue be sure and post it here. I will do the same once I look into it further.

      • Hi Ivan,

        Thanks for the reply. Yep I figured it out. It is in Radian the result I showed you. operandStack = [0.54030230586814]
        In my country we use degree, and that’s why I was lost. 🙂
        Good luck with your studies.

Leave a Reply to gaby Cancel reply

Your email address will not be published. Required fields are marked *

18 + 12 =