As far as I know, there are 4 ways to declare a dictionary in Swift:
var dict1: Dictionary<String, Double> = [:]
var dict2 = Dictionary<String, Double>()
var dict3: [String:Double] = [:]
var dict4 = [String:Double]()
It seems these four options yields the same result.
What's the difference between these?
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]
Related
//First way
var myVar: String = " Hello"
print(myVar)
//Second way
var str = "Hello"
print(str)
I get the same output no matter which of the two I use. What's the difference between them?
These two are basically the same.
When you use var myVar: String = "Hello", you directly tell the swift compiler that your variable is type String.
When you use var myVar = "Hello", you do not specify the type of your variable, so the swift compiler has do do that for you.
Usually, you can get away without declaring your variable type and just have swift do it for you. However, in some cases, namely computed properties and custom classes/structures, you must manually declare your variable to be a specific type.
In your case, either way is fine. The end result is the same, just be aware of the difference for the future.
These two variable are same but with different names :
var myVar
var str
in swift Type doesn't matter that defined because, swift based on value it recognizes what type it is.
Not sure if my title is accurate. Please comment if so will update.
In one method I just create the dictionary and initialize it with ()
In the other I create it and immediately fill it with a key value pair.
What is the difference? Is one prefered over the other?
//initializing dictionary
var airPortCodesInitialize = [Int: String]()
//vs declaring
var airPortCodes: [String: String] = ["SLC": "Salt Lake City", "LAX": "Los Angeles"]
In both cases, you are declaring a dictionary and initializing it. The only difference is that the first line creates an empty dictionary, the second line creates a dictionary filled with key value pairs.
A single declaration looks like this:
var myDictionary: [String: String]
I think you misunderstood what declarations are, so for the rest of this answer, I will compare the line above and your first line.
What is the difference?
A single declaration gives the variable no value, so if you try to use myDictionary immediately after the declaration without initializing it, the compiler gives you an error:
print(myDictionary["Hello"]) // error
Is one prefered over the other?
Most of the time, you should put the initialisation and declaration on the same line like you did in
var airPortCodesInitialize = [Int: String]()
This is more readable.
Sometimes though, you might want different initial values for a constant dictionary depending on a value. Then you must separate the declaration and initialisation:
let myConstantDict: [String: String]
switch something {
case .foo:
myConstantDict = ...
case .bar:
myConstantDict = ...
}
As far as I know there are two ways to create an empty dictionary in swift
var randomDict = [Int:Int]()
or
var randomDict = Dictionary<Int, Int>()
Is there any difference between these? Both versions seems to work just the same.
No, both are same.
From Apple's Book on Swift:
The type of a Swift dictionary is written in full as Dictionary<Key, Value>
You can also write the type of a dictionary in shorthand form as [Key: Value]. Although the two forms are functionally identical, the shorthand form is preferred.
So
var randomDict = [Int:Int]()
and
var randomDict = Dictionary<Int, Int>()
both calls the initializer which creates an empty dictionary and are basically the same in different form.
A third way you could do it is:
var randomDict:[Int:Int] = [:]
They're all equivalent as far as the code goes. I prefer one of the shorthand versions.
I looked through docs some forums and found I can create an array in various ways. I am confused which one should we be using?
var testArray = [Int]()
testArray.append(1)
var anotherTestArray: [Int] = []
anotherTestArray.append(1)
var yetAnotherTestArray: Array<Int> = []
yetAnotherTestArray.append(1)
var yetYetYetAnotherTestArray = Array<Int>()
yetYetYetAnotherTestArray.append(1)
This is not empty array but It keeps it's type for each element to be strictly to an Int
var yetYetAnotherTestArray = [1]
I think the cleanest way to create an array is var testArray: [Int] = []
In swift array objects must be the same type. If you want to store different objects of different types use [AnyObject]. However, you should always know what is coming out of it. Since the returning type value will be AnyObject, you have to cast down the value to the type you want.
I really don't recommend using AnyObject as the type of your arrays unless you really know what you are doing.
Here is an example anyway:
let a: [AnyObject] = [1, "a"]
let b = a[0] // An Int
let c = a[1] // A String
This code works,
let people = ["Tom","Dick","Harry"]
but this code doesn't work, for no apparent reason
let people = []
and nor does this (mutability matters not):
var people = []
The error is "Cannot convert expression's type Array to type 'ArrayLiteralConvertible'", but that makes no sense to me, and none of the other questions that show up in a search address this question.
At first I thought it had to do with type inference, but that proves not to be the issue (at least not simply that!) since although this works (with type specified)
var people:Array = [""]
this does not (with type specified as above but no String given inside the Array):
var people:Array = []
Since the last of these two has the type specified explicitly, it shouldn't need a String passed inside the Array.
Some languages (weirdly!) consider the type of the variable to refer to the type of item inside the array, so I also tried specifying String instead of Array, but got the same results. This first one works and the second doesn't:
var people:String = [""]
var people:String = []
The syntax you are looking for is
let people : [String] = []
or
let people = [String]()
in both case, you can substitute [String] with Array<String>
For this code
let people = []
It is impossible for compiler to figure it out the type of people. What type do you expect it have?
Note Array is not a complete type because it require the generic part. A complete type is like Array<String>
You can do this
let blankArray = [String]()
or ny other type you need.