对 Swift 数组声明感到困惑 [英] Confused about Swift Array Declarations
问题描述
以下有区别吗?
var array1_OfStrings = [String]()
var array2_OfStrings: [String] = []
在 Playground 中的测试表明 1 和 2 相同,但 3 的行为不同.有人可以解释我的区别吗?还有什么是声明 String
空数组的首选方法?
Testing in Playground shows that 1 and 2 are the same but 3 behaves differently.
Can someone explain me the difference please? And also what will be the preferred way to declare an empty array of String
?
推荐答案
前两个效果一样.
声明一个变量
array1_OfStrings
,让它自己选择类型.当它看到[String]()
时,它很聪明地知道这是字符串类型的数组.
declare a variable
array1_OfStrings
, let it choose the type itself. When it sees[String]()
, it smartly knows that's type array of string.
你将变量array2_OfStrings
设置为字符串类型数组,然后通过[]
You set the variable array2_OfStrings
as type array of string, then you say it's empty by []
这是不同的,因为您只是告诉您希望 array3_OfStrings
是字符串类型的数组,而不是给它一个初始值.
This is different because you just tell you want array3_OfStrings
to be type array of string, but not given it an initial value.
我认为第一个推荐为 Swift 编程语言使用它的频率更高.
I think the first one is recommended as The Swift Programming Language uses it more often.
这篇关于对 Swift 数组声明感到困惑的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!