Having Problems calculating the volume with 3 input values. - swift

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 ??.

Related

How do I assign Y to X?

I couldn't figure out how to copy value of variable into another variable in Swift, an example code for this in python would be
def assignVariable():
x=1
y=x
return y
RESULT 1
When I did this it doesn't seem to work in Swift. Is there any solution to this or am I doing something wrong?
Edit: problem is at
var originalCount=countDown
it gave me Use of unresolved identifier 'countDown' but when I assign it literally it works. Here's my swift code
import Cocoa
class MainWindow: NSWindowController {
var hitCount = 0
var started:Bool = false
var timer = 10
var colorList: [NSColor] = [ NSColor.black,NSColor.blue,NSColor.brown,NSColor.cyan,NSColor.darkGray,NSColor.gray,NSColor.green,NSColor.lightGray,NSColor.magenta,NSColor.orange,NSColor.purple,NSColor.red,NSColor.white,NSColor.yellow]
#IBOutlet weak var button1: NSButton!
#IBOutlet weak var scrubber1: NSScrubber!
#IBOutlet weak var display: NSTextField!
override func windowDidLoad() {
super.windowDidLoad()
// Implement this method to handle any initialization after your window controller's window has been loaded from its nib file.
}
var countdown=10
var originalCount=countDown
//(countdown,originalCount) = (10,10) //it works if i use this instead
func startGame(){
if(countDown>0 || started==true){
display.stringValue=String(countDown)
countDown-=1
let seconds = 1.0
DispatchQueue.main.asyncAfter(deadline: .now() + seconds) {
self.startGame()
}
}else{
display.stringValue="Done "+String(hitCount)+" Taps in " + String(originalCount) + "Tap to RESET"
started=false
countDown=10;
}
}
#IBAction func labelPress(_ sender: Any) {
display.stringValue="__RESET__"
hitCount=0
countDown=10
started=false
}
#IBAction func buttonPressed(_ sender: Any) {
if started==false{
startGame()
}
button1.bezelColor = colorList[Int.random(in: 0..<colorList.count)]
started=true
button1.title=String(hitCount)
hitCount+=1
}
}
You can't initialise one variable with another at the top level in your class. Looking at your code I don't think that originalCount needs to be a property, move it inside startGame() instead and make it a local variable and also use let since it isn't changing
var countdown=10
func startGame(){
let originalCount = countDown
if(countDown>0 || started==true){
...
}

Swift/Xcode: trying to access local variable that gets updated in another function

I'm a beginner and I am struggling with a certain problem regarding local variables. Specifically, I am trying to make an app where I test certain fraction questions. So, I need to generate random numbers for the test and access them so that the checker function can make sure the user got the right answer. However, if I generate a new set of numbers when the user clicks "ask question", the other checker function doesn't know what those numbers are... Here is my code below:
class ViewControllerEasy: UIViewController {
#IBOutlet weak var giveQuestionOutlet: UIButton!
#IBOutlet weak var nextButtonOutlet: UIButton!
#IBAction func nextQuestionButton(_ sender: Any) {
nextButtonOutlet.isHidden = true
giveQuestionOutlet.isEnabled = true
easyQuestionResponse.text = ""
easyQuestionLabel.text = ""
resultLabel.text = ""
}
#IBOutlet weak var easyQuestionResponse: UITextField!
#IBOutlet weak var easyQuestionLabel: UILabel!
#IBAction func easyQuestionButton(_ sender: Any) {
let num1 = Int.random(in: 1 ..< 6)
let num2 = Int.random(in: 2 ..< 11)
easyQuestionLabel.text = "What percentage does \(num1) / \(num2) represent? (Round down to the closest whole number)"
}
#IBOutlet weak var resultLabel: UILabel!
#IBAction func checkButton(_ sender: Any) {
let expectedAnswer = ((num1 * 100) / num2)
let expectedAnswer2 = Float(expectedAnswer)
if Float(easyQuestionResponse.text!) == round(expectedAnswer2) {
resultLabel.text = "Great Job! Correct Answer."
nextButtonOutlet.isHidden = false
giveQuestionOutlet.isEnabled = false
}else {
resultLabel.text = "Sorry, that is incorrect. The correct answer was: \(round(expectedAnswer2))%"
nextButtonOutlet.isHidden = false
giveQuestionOutlet.isEnabled = false
}
}
func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
let invalidCharacters = CharacterSet(charactersIn: "0123456789").inverted
return string.rangeOfCharacter(from: invalidCharacters) == nil
}
override func viewDidLoad() {
super.viewDidLoad()
}
}
So, how can I generate new questions when the user clicks the button to ask for it and also make sure that the code can check whether or not the user got the right answer? I tried looking at using a global variable, but that would keep the values same after the first execution of the random numbers call. Thus, I hope someone can help me with this problem. Thanks in advance.

NSPopUpButton selection to Float Swift 4

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
}

Multiply a UI text field with number - Swift

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)
}

Reuse a value from NSSlider in variable

I have a little problem but I can't figured out ...
I code a sort a Shutdown countdown and I need to re-use the variable name "x" in the following code :
#IBAction func valueChange(sender: NSSlider) {
let x = sender.intValue
valueofSlider.stringValue = "\(x)"
}
IBOutlet weak var countDown: NSTextField!
var starter = false;
#IBAction func startCountDown(sender: NSButton) {
starter = true
}
var trigger = 600 //here I put the value myself but i would like
var trigger = (x * 60) //to get the slider value in seconds
First create an Outlet for your slider and then a variable to hold its value. Assign the variable inside valueChanged and now you can use it wherever you want:
#IBOutlet var slider: UISlider!
var sliderValue: Float = 0
#IBAction func valueChanged(sender: AnyObject) {
sliderValue = slider.value
print(sliderValue)
}