1

I want to pass an optional dictionary parameter in Swift function, I tried declaring the function as

 func myFunction(_ type:Int, params:Dictionary<String,Any?>?)

and also

 func myFunc(_ type:Int, params:[String:Any?]?)

I get warning "Expression implicitly coerced from Any? to Any" with first declaration when I try to pass a dictionary but not with second. I need to know what is the difference between the two and why the warning. FYI, here is how I pass the dictionary in both cases:

myFunc(1, params:["key1": value1, "key2": value2])
Deepak Sharma
  • 5,577
  • 7
  • 55
  • 131
  • `["key1", value1, "key2", value2]` is array not dictionary – Nirav D May 20 '17 at 09:01
  • You should avoid using dictionary types with optional values, as the `Dictionary` API uses `nil` to indicate the lack of key for a given value. Having an optional `Value` type therefore will give you double-wrapped optionals, which can cause all sorts confusion. – Hamish May 20 '17 at 09:41
  • But in any case, please provide us with a [mcve]. The code you've shown us is both incomplete (what's `value1` and `value2`?) and incorrect in places – you're trying to pass an array literal into a dictionary parameter, you're missing off the closing `)` on your function call, your two functions have different names (`myFunc` vs. `myFunction`). – Hamish May 20 '17 at 09:43
  • @NiravD Sorry for the typo, I made the correction and now it is correct! – Deepak Sharma May 20 '17 at 10:42

2 Answers2

1

According to Swift documentation, they are identical:

The type of a Swift dictionary is written in full as Dictionary<Key, Value>, where Key is the type of value that can be used as a dictionary key, and Value is the type of value that the dictionary stores for those keys.

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 and is used throughout this guide when referring to the type of a dictionary.

I'm using Xcode Version 8.0 and i couldn't regenerate your issue.

Mo Abdul-Hameed
  • 6,030
  • 2
  • 23
  • 36
0

They are just different syntactic sugar for dictionary declaration and one type will not work in all cases which are kind of a bug.

For Example,

  var msSet = [Vertex<Int> : Double]() 

I have asked a question related to it.

Swift Dictionary Initialization of custom type gives: '>' is not a postfix unary operator error

Rahul
  • 2,056
  • 1
  • 21
  • 37