标准数组,设置,字典变量创建方式Swift编程语言

问题描述:

我是Swift语言的初学者。有许多方法可以在其中声明/创建变量。请填写下面的代码。我想知道我可以声明数组,集合和字典的所有方法。标准数组,设置,字典变量创建方式Swift编程语言

var arr1 : [Int] 
var arr2 = [Int]() 
var arr3 : Array<Int> 
var arr4 = [1,2,3,4] 
var arr5 : Array = [1,2,3,4] 
var arr6 : [Array<Int>] 

var dict1 : [Int:Int] 
var dict2 = [Int:Int]() 
var dict3 : Dictionary<Int,Int> 
var dict4 = [1 : 2,3 : 4] 
var dict5 : Dictionary = [1 : 2,3 : 4] 
var dict6 : [Dictionary<String, Int>] 
var dict7 = [Dictionary<String, Int>]() 
var dict8 = Dictionary<Int,Int>() 

var set1 : Set<Int> 
var set2 = Set<Int>() 
var set3 : Set = [1,2,3] 
var set4 : [Set<Int>] 
var set5 = [Set<Int>]() 
+1

“请填写下面的代码。”那有什么意思? – Alexander

+0

添加一个方法来创建一个变量 –

+1

...你有很多,你在找什么? – Alexander

您的列表包含形式声明以及声明和初始化后的可变

两个替代形式的阵列和字典

var arr7 : [Int] = [] // same as arr2 

var dict9 : [Int:Int] = [:] // same as dict2, dict8 

很多这些都不是有效的,甚至:

var arr1 : [Int] //an undefined var of type Int array, see note #1 
var arr2 = [Int]() //an array of type Int with no elements 
var arr3 : Array<Int> //same as arr1 
var arr4 = [1,2,3,4] //an array of 4 Ints 
var arr5 : Array = [1,2,3,4] //an array of 4 Ints with a redundant type annotation 
var arr6 : [Array<Int>] //an array of arrays of Ints 

var dict1 : [Int:Int] //an undefined var of type Dictionary (mapping Int keys to Int keys), see note #1 
var dict2 = [Int:Int]() //an empty dictionary mapping Int keys to Int values 
var dict3 : Dictionary<Int,Int> //same as dict1 
var dict4 = [1 : 2, 3 : 4] //a dictionary with two Int : Int mappings 
var dict5 : Dictionary = [1 : 2,3 : 4]//a dictionary with two Int mappings and a redundant type annotation 
var dict6 : [Dictionary<String, Int>] //an undefined var of type array of Dictionaries from String keys to Int values. 
var dict7 = [Dictionary<String, Int>]() //an empty array of dictionaries mapping String keys to Int values 
var dict3 : Dictionary<Int,Int> //dict 3 repeated from above? 
var dict8 = Dictionary<Int,Int>() //an empty dictionary mapping Int keys to Int values 

var set1 : Set<Int> //an undefined var of type Set (of Int), see note #1 
var set2 = Set<Int>() //an empty set of Int 
var set3 : Set = [1,2,3] //a set of 3 Ints 
var set4 : [Set<Int>] //an undefined var of type Array (of Sets of Ints), see note #1 
var set5 = [Set<Int>]() //an empty array of Sets of Ints 

  1. 这些变量有类型注释,但没有初始化。他们不能从直到一个有效的值分配给它们

这说明[]符号的一个根本性的误解(阵列,字典和集合),然后键入注释读取。我强烈建议你阅读语言指南。

+0

请注意,只有类型注释的变量,例如'var arr1:[ Int]'会自行编译 - 只是在你初始化之前你不能使用它。 – Hamish

+0

哦,你是对的。定影。 – Alexander

+0

谢谢你的回答,但代码编译得很好1 dict3s –