Different ways to initialize a dictionary in Swift?

前端 未结 1 534
一整个雨季
一整个雨季 2020-12-10 02:51

As far as I know, there are 4 ways to declare a dictionary in Swift:

var dict1: Dictionary = [:]
var dict2 = Dictionary

        
相关标签:
1条回答
  • 2020-12-10 03:24

    All you're doing is noticing that you can:

    • Use explicit variable typing, or let Swift infer the type of the variable based on the value assigned to it.

    • Use the formal specified generic struct notation Dictionary<String,Double>, or use the built-in "syntactic sugar" for describing a dictionary type [String:Double].

    Two times two is four.

    And then there are in fact some possibilities you've omitted; for example, you could say

    var dict5 : [String:Double] = [String:Double]()
    

    And of course in real life you are liable to do none of these things, but just assign an actual dictionary to your variable:

    var dict6 = ["howdy":1.0]
    
    0 讨论(0)
提交回复
热议问题