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

时间:2016-07-04 13:59:54

标签: swift

我是Swift语言的初学者。有许多方法可以在其中声明/创建变量。请填写下面的代码。我想知道我可以声明Arrays,Sets和Dictionaries的所有方法。

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>]()

2 个答案:

答案 0 :(得分:1)

其中许多甚至都没有效:

var arr1 : [Int] //an uninitialized 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 uninitialized 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 uninitialized 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 uninitialized 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 uninitialized var of type Array (of Sets of Ints), see note #1
var set5 = [Set<Int>]() //an empty array of Sets of Ints

注释

  1. 这些变量具有类型注释,但没有初始化。在为其分配有效值之前,无法读取它们
  2. 这表明对[]符号(对于数组,字典和集合)和类型注释的基本误解。我强烈建议你阅读语言指南。

答案 1 :(得分:1)

您的商家信息包含声明的表单以及声明和初始化变量

后者的两种替代形式,用于数组和字典

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

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