Reputation: 79
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var Screen: UILabel!
var firstNumber = Float()
var secondNumber = Float()
var result = Float()
var operation = ""
var isTypingNumber = false
@IBAction func Number(sender: AnyObject) {
isTypingNumber = false
var number = sender.currentTitle
if isTypingNumber == true {
Screen.text = Screen.text! + number!!;
} else {
Screen.text = number!!;
}
isTypingNumber = true
}
@IBAction func Operation(sender: AnyObject) {
operation = sender.currentTitle!!
isTypingNumber = false
firstNumber = Screen.text!.toInt()!
}
@IBAction func Equals(sender: AnyObject) {
secondNumber = Screen.text!.toInt()!
isTypingNumber = false
if operation == "+" {
result = firstNumber + secondNumber;
} else if operation == "-" {
result = firstNumber - secondNumber;
} else if operation == "x" {
result = firstNumber * secondNumber;
} else if operation == "/" {
result = firstNumber / secondNumber;
}
Screen.text = "\(result)"
}
@IBAction func Clear(sender: AnyObject) {
firstNumber = 0
secondNumber = 0
result = 0
Screen.text = "\(result)"
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
This is my code. I am always getting the errors 'Int' is not convertible to 'Float' on firstNumber = Screen.text!.toInt()! and secondNumber = Screen.text!.toInt()!
I am trying to display a float on a UILabel(Screen). How would I do it?
Can someone tell me how to work a float in UILabel. This is Swift.
Thanks, Rohit
Upvotes: 3
Views: 6970
Reputation: 2643
You can try this :
@IBAction var label:UILabel!
var a:Float=1938.22
override func viewDidLoad(){
super.viewDidLoad()
label.text="\(a)"
}
Upvotes: 1
Reputation: 24572
You are trying to assign an Int value to a variable of type Float
. This is not allowed in swift. You can try
let floatValue = (label.text as NSString).floatValue
and to display the floatValue
in a UILabel
, you can use string interpolation in swift.
label.text = "\(floatValue)"
To convert an Int
to a Float
you can do
floatValue = Float(intValue)
Upvotes: 9
Reputation: 107131
Issue is you declared firstNumber
as Float, but you are assigning an Int value to that variable.
Change:
firstNumber = Screen.text!.toInt()!
to
firstNumber = (Screen.text! as NSString).floatValue
Note:
Similar applies to secondNumber
also.
Upvotes: 1