他们有什么不同?我有点困惑,因为它们似乎是类似的概念.
来自Swift自己的
documentation:
类型安全
Swift是一种类型安全的语言.类型安全语言鼓励您清楚代码可以使用的值的类型.如果您的部分代码需要String,则不能错误地将其传递给Int.
var welcomeMessage: String welcomeMessage = 22 // this would create an error because you //already specified that it's going to be a String
类型推断
如果未指定所需的值类型,Swift将使用类型推断来计算出适当的类型.类型推断使编译器能够在编译代码时自动推断出特定表达式的类型,只需检查您提供的值即可.
var meaningOfLife = 42 // meaningOfLife is inferred to be of type Int meaningOfLife = 55 // it Works,because 55 is an Int
类型安全&一起输入推理
var meaningOfLife = 42 // 'Type inference' happened here,we didn't specify that this an Int,the compiler itself found out. meaningOfLife = 55 // it Works,because 55 is an Int meaningOfLife = "SomeString" // Because of 'Type Safety' ability you will get an //error message: 'cannot assign value of type 'String' to type 'Int''
专家提示:
代码必须进行的类型推断越少,编译速度就越快.因此,建议避免收集文字.收集的时间越长,其类型推断变得越慢……
不错
let names = ["John","Ali","Jane"," Taika"]
好
let names : [String] = ["John"," Taika"]