简体   繁体   English

swift“ variable:Type”和“ variable as Type”有什么区别

[英]what is the difference between “variable:Type” and “variable as Type” swift

What is the difference between: 之间有什么区别?

let variable:Double = 23

and "as Type"? 和“作为类型”?

let variable = 23 as Double

let variable:Double = 23 let变量:Double = 23

Declaring variable in this way is called Type Annotation in which we are telling complier explicitly that variable is type of Double instead of compiler referring to type of assigned value. 以这种方式声明变量称为类型注释 ,其中我们明确告诉编译器变量是Double类型,而不是编译器引用赋值类型。

let variable = 23 as Double 让变量= 23作为双精度

This is called type casting .As per definition in Swift, 这称为类型转换 。根据Swift中的定义,

Type casting in Swift is implemented with the is and as operators. Swift中的类型转换使用is和as运算符实现。 These two operators provide a simple and expressive way to check the type of a value or cast a value to a different type. 这两个运算符提供了一种简单而富有表现力的方式来检查值的类型或将值转换为其他类型。

So these are not different in terms of functionality. 因此,它们在功能上没有什么不同。 Using first way, we are adding redundant token for declaring a constant as type inference would detect type automatically by value. 使用第一种方法,我们添加了冗余令牌来声明一个常量,因为类型推断将通过值自动检测类型。

By Second way, we are forcing a constant to have a kind of value which would be useful in case of superClass/Subclass type casting. 通过第二种方式,我们强制常量具有一种值,该值在superClass / Subclass类型转换的情况下将很有用。

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

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