0

So I'm trying to learn swift and on button action, I want to declare a variable as an integer that collects the value from a text field, calculates if it is not nil and prints the value. Why is it asking me to make the variable constant?

This what I've tried

import UIKit

class ViewController: UIViewController {

    @IBOutlet weak var enterAge: UITextField!
    @IBOutlet weak var catAge: UILabel!

    @IBAction func findAge(sender: AnyObject) {

        var newage = Int(enterAge.text!)

        if newage! == 0
        {

       var catyears = newage! * 7
        catAge.text = "Your cat is \(catyears) in age"
        }

        else
        {

            catAge.text = "Please enter a whole number"
        }

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


}

Xcode version 7.1 The error: enter image description here

Thanks

2
  • 1
    That isn't a error, it's more of a friendly message. newage is never mutated, so there's no need to use var, making it constant would work fine Commented Mar 7, 2016 at 1:33
  • If you want to learn Swift read at least chapter The Basics of the Swift Language Guide to understand the basic definitions and rules. Commented Mar 7, 2016 at 5:44

2 Answers 2

7

It is a warning, not an error: your program will still compile and run even if you ignore it (but down the road, it's best practice if you don't).

It is telling you that because your 'variable' gets assigned its initial and only value once, and thereafter it is only read from (never written to). Hence, it doesn't need to be a variable; a constant will do (and better reflects the intent of your program).

Sign up to request clarification or add additional context in comments.

Comments

1

var - allows you to change the value of the object or variable created after assignment,

where,

let is constant and can be initialised only once. your snippet show us you are using your variable to just store the value got from textfield and never changed later there after, consider your requirement and usage system is advising you to change your variable to constant. changing variable to constant will not effect you code.

if you want to check then just write

newage = newage + 0

this will result same but see the warning is gone now, we are assigning/changing the value of variable.

hope this explains why you are getting the warning..

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.