jay dale
jay dale

Reputation: 1

How do I correctly calculate age in Swift?

I'm looking to make a button calculate different equations.

What I have is any number I put into a text field it gets multiplied by 7.

But I'm looking to change it completely: I'd like to remove the multiply function altogether.

If the user enters 1 then the button press simply shows 7 If the user enters 2 then the button press simply shows 8 If the user enters 3 then the button press simply shows 9

Basically put canned responses in for 10 options (the user will be asked to enter 1 - 10) and I'll spit out the appropriate answer in a label box.

class ViewController: UIViewController {

    @IBOutlet weak var CatAge: UITextField!
    @IBOutlet weak var message: UILabel!

    @IBAction func ButtonPressed(sender: AnyObject) {
        var age = CatAge.text.toInt()
        age = age! * 7
        message.text = "Thats equal to \(age!) in cat years"
   }
}

Upvotes: 0

Views: 681

Answers (2)

vacawama
vacawama

Reputation: 154631

You could do this simply with a dictionary.

@IBAction func ButtonPressed(sender: AnyObject) {
    let convert = [1:7, 2:8, 3:9, 4:10, 5:11, 6:12, 7:13, 8:14, 9:15, 10:16]
    if let age = convert[CatAge.text.toInt() ?? 0] {
        message.text = "Thats equal to \(age) in cat years"
    } else {
        message.text = "Invalid value"
    }
}

Here I have used the nil coalescing operator ?? to safely unwrap CatAge.text.toInt() if there is a value, otherwise it will be 0 if the text field couldn't be converted to an Int. If the text field contains an Int that isn't in the dictionary, then the lookup in convert will return nil. In that case, the optional binding will fail and the message will be "Invalid value".

Upvotes: 1

AstroCB
AstroCB

Reputation: 12367

If I'm reading this correctly, all you want it to do is add 6 to whatever they type in. In that case, your answer is simple:

@IBAction func ButtonPressed(sender: AnyObject) {
    var age: Int = CatAge.text.toInt()!
    age += 6
    message.text = "Thats equal to \(age) in cat years"
}

Otherwise, if you're looking for something more dependent on what they actually type in, you might be looking for a switch statement, which goes something like this:

switch age {
    case 1:
        age = 7
    case 2:
        age = 10
    case 3:
        age = 15
    case 4:
        age = 22
    case 5:
        age = 27
    case 6:
        age = 33
    case 7:
        age = 40
    case 8:
        age = 46
    case 9:
        age = 51
    case 10:
        age = 60
    default:
        age = 0
}

Upvotes: 2

Related Questions