-1

I am trying to build a calculator in swift, but it does not seem to work. I don't really know how to explain it but here is an example: If I sum up 1 + 2 it returns 12 instead of 3.

Here is my code. Please note that num1 is the first part of the operation and num2 the second.

var num1 : String = ""
var num2 : String = ""

@IBOutlet weak var label: UILabel!

@IBAction func button(sender: UIButton) { 
    var currentnumber = self.label.text
    var sendertag = String(sender.tag)
    self.label.text = currentnumber! + sendertag
}

@IBAction func sum(sender: UIButton) {    
    num1 = self.label.text!
    self.label.text = ""
}

@IBAction func enter(sender: UIButton) {
    num2 = self.label.text!

    num1.toInt()
    num2.toInt()

    self.label.text = num1 + num2
}
rmaddy
  • 314,917
  • 42
  • 532
  • 579
Alec Attie
  • 37
  • 1
  • 5
  • 1
    Possible duplicate of [Get number value from string in swift](http://stackoverflow.com/questions/24019236/get-number-value-from-string-in-swift) – Amadan Nov 11 '15 at 01:58
  • @user3457759 thanks for the reply to all of you. Your code sounds reasonable but it still marks an error. it says to delete the exclamation marks but if i do that then it says that binary operator '+' cannot be applied to two int operants. Sorry for this i am completely new to Swift. Thanks – Alec Attie Nov 11 '15 at 04:41
  • @anhtu thanks for the reply. When i execute the code it marks an error: binary operator '+' cannot be applied to two int operants – Alec Attie Nov 11 '15 at 04:42

2 Answers2

1

The problem is because you're trying to sum integers but you're actually appending String since when you do

self.label.text = currentnumber! + sendertag

Both are Strings (you can check the type on Xcode).

What you want to do is add this two numbers so you have to parse them to Integer, you can achieve this by doing the following

self.label.text = String(Int(current number!)! + Int(sendertag)!)

This is, first parsing to Integer both string and adding them up and then parse the result back to string because the text of the label has to be a string.

Miguelme
  • 609
  • 1
  • 6
  • 17
0

When you assign sum of two integer numbers into string value, It may implicitly type casting from Int to String

Replace

  self.label.text = num1 + num2

with

var result: Int =num1+num2
self.label.text=String(result)

In objective c it shows up error: Xcode 4.2 or higher

Implicit conversion of 'int' to 'NSString *' is disallowed with ARC

Saranjith
  • 11,242
  • 5
  • 69
  • 122