在苹果的Swift语言中,let和var有什么区别?
在我的理解中,它是一种编译语言,但它不在编译时检查类型。这让我很困惑。编译器如何知道类型错误?如果编译器不检查类型,这不是生产环境的问题吗?
当我试图给let赋值时给出了这个错误:
不能给属性赋值:'variableName'是一个'let'常量 将'let'改为'var'使其可变
在苹果的Swift语言中,let和var有什么区别?
在我的理解中,它是一种编译语言,但它不在编译时检查类型。这让我很困惑。编译器如何知道类型错误?如果编译器不检查类型,这不是生产环境的问题吗?
当我试图给let赋值时给出了这个错误:
不能给属性赋值:'variableName'是一个'let'常量 将'let'改为'var'使其可变
当前回答
主要的区别是var变量值可以改变,而let不能。如果你想让一个用户输入数据,你可以使用var来改变值,使用let数据类型变量来改变值。
var str = "dog" // str value is "dog"
str = "cat" // str value is now "cat"
let strAnimal = "dog" // strAnimal value is "dog"
strAnimal = "cat" // Error !
其他回答
在swift语言中,let是一个常量,意思是不能重新分配,但var可以重新分配
let question = "what is the difference between let and var?"
question = "another question" // this line cause syntax error
var answer = "let is constant and var is simple variable"
answer = "let can't be reassigned var can be reassigned" // this line will be excecuted
Var是唯一的方法来创建一个变量在swift。Var并不像javascript这样的解释性语言那样意味着动态变量。例如,
var name = "Bob"
在本例中,变量名称的类型推断为name类型为String,例如,我们也可以通过显式定义type来创建变量
var age:Int = 20
现在如果你将一个字符串赋值给age,编译器就会给出错误。
Let用于声明常量。例如
let city = "Kathmandu"
或者我们也可以,
let city:String = "Kathmandu"
如果您试图更改city的值,则会在编译时给出错误。
Let用于定义常量,var用于定义变量。
和C语言一样,Swift也使用变量来存储和引用变量的值。Swift还大量使用了值不可更改的变量。这些被称为常量,比c中的常量强大得多。当你处理不需要更改的值时,整个Swift都使用常量,使代码更安全、更清晰。 https://docs.swift.org/swift-book/LanguageGuide/TheBasics.html
Let关键字定义一个常量
let myNum = 7
所以myNum之后不能更改;
但是var定义了一个普通变量。
常量的值不需要在编译时知道,但是必须为它赋值一次。
你可以使用几乎任何你喜欢的字符作为常量和变量名,包括Unicode字符;
e.g.
var x = 7 // here x is instantiated with 7
x = 99 // now x is 99 it means it has been changed.
但是如果我们采取let,那么……
let x = 7 // here also x is instantiated with 7
x = 99 // this will a compile time error
Let定义一个“常数”。它的值设置一次且仅一次,但不一定在声明时设置。例如,你可以使用let来定义类中必须在初始化时设置的属性:
class Person {
let firstName: String
let lastName: String
init(first: String, last: String) {
firstName = first
lastName = last
super.init()
}
}
通过这种设置,在调用(例如)Person(第一个:“Malcolm”,最后一个:“Reynolds”)创建Person实例后赋值给firstName或lastName是无效的。
您必须在编译时为所有变量(let或var)定义一个类型,并且任何试图设置变量的代码只能使用该类型(或子类型)。可以在运行时赋值,但在编译时必须知道其类型。