简体   繁体   English

在Swift中将变量声明为Integer

[英]Declaring a variable as Integer in Swift

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: Xcode 7.1版错误: 在此处输入图片说明

Thanks 谢谢

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). 一个常数将起作用(并更好地反映您程序的意图 )。

var - allows you to change the value of the object or variable created after assignment, var-允许您更改分配后创建的对象或变量的值,

where, 哪里,

let is constant and can be initialised only once. let是常数,只能初始化一次。 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.. 希望这能解释您收到警告的原因。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM