Just starting learning swift but stuck when trying to multiply an input with another number and display on a label. I get the error that the number isn't a string and tried to cast but didn't work.
class ViewController: UIViewController {
#IBOutlet weak var entry: UITextField!
#IBOutlet weak var answer: UILabel!
#IBAction func button(_ sender: Any) {
answer.text = entry.text * 2
}
}
You should cast the text into a Double, an Int etc., then convert the calculation to a string.
if let entry = Double(entry.text) {
answer.text = "\(entry * 2)"
}
or
if let entry = Int(entry.text) {
answer.text = "\(entry * 2)"
}
If you know that the entry will hold a number
answer.text = String(Int(entry.text)! * 2)
Using optional unwrapping instead
if let num = Int(entry.text) {
answer.text = String(num * 2)
}
Related
i have a label and a UIStepper, i need to increase the number of that label without lossing the letters ( Kd ) . my label will be like this "5.000 Kd" and when i increase the number i don't want to loss the ( Kd ) label.
this is my code
import UIKit
import GMStepper
class ViewController: UIViewController {
#IBOutlet var stepper: GMStepper!
#IBOutlet var price: UILabel!
override func viewDidLoad() {
super.viewDidLoad()
}
#IBAction func stepper(_ sender: Any) {
let label = "5.000 Kd" as NSString
price.text! = String(label.doubleValue * stepper.value)
}
}
If you are hard-coding the string contents of the label, just maintain a numeric value and rebuild the label contents each time that value changes:
class ViewController: UIViewController {
#IBOutlet var stepper: GMStepper!
#IBOutlet var priceLabel: UILabel!
var price: Double = 5.0
#IBAction func stepper(_ sender: Any) {
let newValue = price * stepper.value
//Format the price with 3 decimal places
let priceString = String(format: "%.3f", newValue)
Construct a string with the formatted price and " Kd" and put it in the label
priceLabel.text = "\(priceString) Kd")
}
}
Consider using NumberFormatter to format currency:
let cf = NumberFormatter()
cf.currencyCode = "KWD"
cf.numberStyle = .currency
cf.string(from: 5000)
That respects the user's Locale.
I want to accept user input in a range, but keep on getting error:
Cannot convert value of type Range<Int32> to expected argument type Range<_>
I am learning Swift but I did not understand the different scenarios to convert UITextField to text and maybe integer.
class ViewController: UIViewController {
#IBOutlet weak var Range1: UITextField!
#IBOutlet weak var Range2: UITextField!
#IBOutlet weak var TheNUmber: UITextField!
#IBOutlet weak var OutletLabel: UILabel!
#IBAction func Guess(_ sender: UIButton) {
var R1 = (Range1.text! as NSString).intValue
var R2 = (Range2.text! as NSString).intValue
//print(R1, " ", R2)
var answer = Int.random(in: R1..<R2)
// I tried my best to use custom range from UItext field but did not work.
//I need more help.
print ("Random Number: \(answer)")
var turn = 0;
if(((R1>1)&&(R1<1000))&&((R2>1)&&(R2<1000))){
for i in 1...5{
let guess = (TheNUmber.text! as NSString).intValue
turn = i;
//let guess = (TheNUmber.text! as NSString).intValue
if(guess == answer){
OutletLabel.text = ("Yes, it is \(answer).")
OutletLabel.text = ("It took you \(turn) tries.")
break
}
else if(guess>answer){
OutletLabel.text = ("Lower!")
}
else if (guess<answer){
OutletLabel.text = ("Higher!")
}
else{
continue;
}
}
if (turn > 5){
OutletLabel.text = ("Sorry, it was \(answer).")
}
}
else{
OutletLabel.text = ("Keep the numbers between 1 and 100.")
}
}
#IBAction func Reset(_ sender: Any) {
self.Reset (sender)
}
I am not sure about this error. Please help me with the range.
The problem is that intValue returns an Int32, not an Int. So change
var R1 = (Range1.text! as NSString).intValue
var R2 = (Range2.text! as NSString).intValue
var answer = Int.random(in: R1..<R2)
To
let R1 = Int((Range1.text! as NSString).intValue)
let R2 = Int((Range2.text! as NSString).intValue)
let answer = Int.random(in: R1..<R2)
Even better, don't use NSString or intValue. Use Swift.
let R1 = Int(Range1.text!)!
let R2 = Int(Range1.text!)!
let answer = Int.random(in: R1..<R2)
Be aware that this code can crash — for example, if the user types "howdy" instead of an integer. But you need to deal with that.
Your code has other issues, but at least you will get past this one.
I am trying to get a String value to a Float value from a NSPopUpButton.
E.g. I have 3 number selections. 50, 20, 10. When the user selects one of the numbers I would like a calculation made into a Float value.
I know this may be something very simple but I am new and I can't find anything on Stackoverflow. Any help would be appreciated. Here is an example of the code I have.
#IBOutlet weak var userInput: NSTextField!
#IBOutlet weak var result: NSTextField!
#IBOutlet weak var userMenuSelection: NSPopUpButton!
override func viewDidLoad() {
super.viewDidLoad()
userMenuSelection.removeAllItems()
userMenuSelection.addItems(withTitles: ["50", "20", "10"])
}
#IBAction func pushButtonforResult(_ sender: Any) {
/*
Not sure how to take the selected userMenuSelection and multiply it by the users input to get my result in a float.
E.g. look below. This of course does not work because the menu items are strings.
*/
result.floatValue = userMenuSelection * userInput.floatValue
}
Hope this makes sense to what I am asking.
As you see, your userMenuSelection has titles representing the Float values as String.
You can simply retrieve the selected title and convert it to Float:
#IBAction func pushButtonforResult(_ sender: Any) {
var selectedValue = Float(userMenuSelection.titleOfSelectedItem ?? "0") ?? 0.0
result.floatValue = selectedValue * userInput.floatValue
}
You can try
let arr = ["50", "20", "10"]
//
#IBAction func pushButtonforResult(_ sender: NSPopUpButton) {
let selectedValue = Float(arr[sender.selectedTag()])!
Result.floatValue = selectedValue * userInput.floatValue
// OR
let selectedValue = Float(sender.selectedItem!.title)!
result.floatValue = selectedValue * userInput.floatValue
}
i'm a fairly new programmer and i've just started on Xcode. Atm i am trying to make a calculator that can calculate the total volume from 3 input values (Height, length & width) but i can't seem to make it calculate it. right now i am able to enter a value and click the button and then it crashes.
Thanks in advance!
here is my code:
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
}
override var representedObject: Any? {
didSet {
// Update the view, if already loaded.
}
}
#IBOutlet weak var HeightInput: NSTextField!
#IBOutlet weak var LengthInput: NSTextField!
#IBOutlet weak var WidthInput: NSTextField!
#IBOutlet weak var Result: NSTextField!
#IBAction func Calculate(_ sender: Any) {
var height = Int(HeightInput.stringValue)
var width = Int(WidthInput.stringValue)
var length = Int(LengthInput.stringValue)
if height == 0
{
Result.stringValue = "Error"
}
else{
var result = width! * height! * length!
Result.stringValue = "the volume is: \(result)"
}
}
Try something like this.
#IBAction func Calculate(_ sender: Any) {
let height = Int(HeightInput.stringValue) ?? 0
let width = Int(WidthInput.stringValue) ?? 0
let length = Int(LengthInput.stringValue) ?? 0
let result = height * width * length
if result == 0 {
Result.stringValue = "Error"
else {
Result.stringValue = "The volume is: \(result)"
}
}
When converting your label value to an integer, it will return an optional (meaning it could be nil). When you are calculating your result, you are force-unwrapping these optionals with the !.
I recommend conditionally unwrapping these values. Using ?? meaning that if the value is nil, it will default to whatever you put after the ??.
I am having problems with calling the function in Swift, when building an iOS app.
#IBOutlet weak var vyseHypoteky: UITextField!
#IBOutlet weak var dobaSplaceni: UITextField!
#IBOutlet weak var urokovaSazba: UITextField!
#IBOutlet weak var mesicniSplatka: UITextField!
#IBAction func zmenaVyseHypoteky(sender: UISlider) {
var currentValue = Int(sender.value)
vyseHypoteky.text = "\(currentValue)"
vypoctiSplatku()
}
#IBAction func zmenaDobySplaceni(sender: UISlider) {
var currentValue = Int(sender.value)
dobaSplaceni.text = "\(currentValue)"
}
#IBAction func zmenaUrokoveSazby(sender: UISlider) {
var currentValue = Int(sender.value)
urokovaSazba.text = "\(currentValue)"
}
func vypoctiSplatku () {
let HU:Int? = vyseHypoteky.text.toInt()
let ipa:Int? = urokovaSazba.text.toInt()
let n:Int? = dobaSplaceni.text.toInt()
var ipm = ipa! / 12
var zavorka = 1+ipm
var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n)
var citatel = HU! * ipm * vypoctenaZavorka
var jmenovatel = vypoctenaZavorka - 1
var splatka = citatel / jmenovatel
mesicniSplatka.text = ("\splatka")
}
func mocnina (mocnenec: Int, mocnitel: Int) -> Int {
var mocnina = 1
for _ in 1...mocnitel {
mocnina *= mocnenec
}
return mocnina
}
The app is calculating a number by my formula. I want to use my function to calculate the x^y, this the "mocnina" function where I want to use two int, the x is "mocnenec" and the y is "mocnitel".
And finally I want to send the final int from variable "splatka" to text inout filed "mesicniSplatka".
But I am getting errors in calling the function "mocnina" --> var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n)
Extraneous argument label 'mocnenec:' in call
Value of optional type 'Int?' not unwrapped; did you mean to use '!' or '?'?
and in the end with mesicniSplatka.text = ("\splatka")
Invalid escape sequence in literal
How to fix it? Thx for helping a total newbie :)
The problem is that n is a wrapped:
var n:Int?
So you have a few options, you can either change your code to unwrap it when you use it (probably a good idea to check for nil before doing this as this will cause an exception if n is nil):
var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n!)
Or you can unwrap it when you create it:
let n:Int = dobaSplaceni.text.toInt()!
If you'd like to better understand "when to use optionals", I've written a very long explanation to this question on the subject: UIViewController variables initialization
In your code, n is declared of type Int?, it means "Optional Int". This is normal because the toInt() function is not guaranteed to succeed, and might return nil if the text is not convertible to an integer. So, you need to unwrap it first, like this: var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n!). Or, if you're not sure the conversion from string succeeded, do something like this:
let HU:Int? = vyseHypoteky.text.toInt()
let ipa:Int? = urokovaSazba.text.toInt()
let n:Int? = dobaSplaceni.text.toInt()
if ipa != nil {
var ipm = ipa! / 12
var zavorka = 1+ipm
if n != nil {
var vypoctenaZavorka = mocnina(mocnenec: zavorka, mocnitel: n)
// etc...
}
}