# Dictionary initialization refinement suggestion

**URL:** <https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025>\
**Category:** Discussion\
**Tags:** init, optional, dictionary\
**Created:** [December 13, 2021, 2:10pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025 "2021-12-13T14:10:39Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [December 13, 2021, 2:10pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/1 "2021-12-13T14:10:39Z")

</div>

Can we do a minor change to swift to treat optional values in dictionary initialisers as "no value"? Example below demonstrates the issue, where instead of a nice and concise first version I have to drop to a more verbose second version which also has an unfortunate consequence that the value becomes "var" (even if it could have been "let"). Besides it's more error prone (e.g. possible to make a typo and use the same key twice, which would be impossible in the first version of the code due to a runtime check for duplicated dictionary keys):

```
func foobar() {
    var foo: String
    var bar: String?
    var baz: String?
    
    let elements: [String: String] = [
        "foo" : foo,
        "bar" : bar, // Error: Cannot convert value of type 'String?' to expected dictionary value type 'String'
        "baz" : baz // Error: ditto
    ]
    
    var elements2: [String: String] = [
        "foo" : foo
    ]
    elements2["bar"] = bar
    elements2["baz"] = baz
    // Note that I can but I don't have to do the "if let" dance here, as dictionary
    // understands my intent here.
}

```

---

<div class="post-metadata">

**Author:** ![michelf](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/michelf/32/1180_2.png) [@michelf](https://forums.swift.org/u/michelf)\
**Post date:** [December 13, 2021, 2:53pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/2 "2021-12-13T14:53:05Z")

</div>

Not exactly what you're looking for, but this is what I use:

```swift
struct Attributes: ExpressibleByDictionaryLiteral {
	var dictionary: [String: String]

	init(dictionaryLiteral elements: (String, String?)...) {
		let keysAndValues = elements.compactMap { pair in
			pair.1.map { (pair.0, $0) }
		}
		dictionary = Dictionary(keysAndValues) { a, b in
			fatalError("non-unique key")
		}
	}
}

let attr: Attributes = [
	"abc": nil,
	"def": "ghi",
]
print(attr.dictionary)

```

---

<div class="post-metadata">

**Author:** ![anon9791410](https://avatars.discourse-cdn.com/v4/letter/a/9fc348/32.png) [@anon9791410](https://forums.swift.org/u/anon9791410)\
**Post date:** [December 13, 2021, 5:09pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/3 "2021-12-13T17:09:24Z")

</div>

Is `Attributes` useful outside of Dictionary initialization? I'd like to see more work put into literal expressibility, but without that, `compactMapValues` seems simpler to me.

```swift
let elements = Dictionary([
  "foo": foo,
  "bar": bar,
  "baz": baz
])

```

```swift
extension Dictionary {
  init(_ dictionary: [Key: Value?]) {
    self = dictionary.compactMapValues { $0 }
  }
}

```

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [December 14, 2021, 10:15pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/4 "2021-12-14T22:15:06Z")

</div>

To sum up we have these options:

```
var foo: String = ""
var bar: String?
var baz: String?

let elements: [String: String] = [
    "foo": foo,
    "bar": bar, // Error: Cannot convert value of type 'String?' to expected dictionary value type 'String'
    "baz": baz // Error: Cannot convert value of type 'String?' to expected dictionary value type 'String'
]

// Workaround #1
let attributes1: Attributes = [
    "foo": foo,
    "bar": bar,
    "baz": bar
]
let elements1: [String: String] = attributes1.dictionary

// Workaround #1can also be turned into a more compact form with the help of `init(_ attributes: Attributes)`

// Workaround #2
let elements2 = Dictionary([
    "foo": foo,
    "bar": bar,
    "baz": baz
])

// Workaround #3
let elements3: [String: String] = [
    "foo": foo,
    "bar": bar,
    "baz": baz
].compactMapValues { $0 }

```

I'd still say that having this refinement of swift is worthwhile but obviously it's not pressing given we have these great workarounds.

---

<div class="post-metadata">

**Author:** ![jrose](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/jrose/32/408_2.png) [@jrose](https://forums.swift.org/u/jrose)\
**Post date:** [December 14, 2021, 10:58pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/5 "2021-12-14T22:58:46Z")

</div>

Sometimes you might _want_ a dictionary with optional values, so I wouldn't want to make this the default behavior, and then I think it's pretty subtle if it's based on a contextual type, whether it's explicitly written or not.

---

<div class="post-metadata">

**Author:** ![tera](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/tera/32/38201_2.png) [@tera](https://forums.swift.org/u/tera)\
**Post date:** [December 14, 2021, 11:09pm UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/6 "2021-12-14T23:09:15Z")

</div>

> [@jrose](#):
>
> Sometimes you might _want_ a dictionary with optional values

It's true (probably in 1% of cases, but still), and the change is not going to amend this. Whether the type annotation is implicit or inferred - the old behaviour is preserved:

```
var foo: String
var bar: String?
var baz: String?

let elements: [String: String] = [
    "foo" : foo,
    "bar" : bar, // Error currently
    "baz" : baz // Error currently
]

let elements: [String: String?] = [
    "foo" : foo,
    "bar" : bar, // currently OK
    "baz" : baz // currently OK
]

let elements = [// treated as [String: String?]
    "foo" : foo,
    "bar" : bar, // currently OK
    "baz" : baz // currently OK
]

```

---

<div class="post-metadata">

**Author:** ![valentinradu](https://sea2.discourse-cdn.com/swift/user_avatar/forums.swift.org/valentinradu/32/23005_2.png) [@valentinradu](https://forums.swift.org/u/valentinradu)\
**Post date:** [December 15, 2021, 12:38am UTC](https://forums.swift.org/t/dictionary-initialization-refinement-suggestion/54025/7 "2021-12-15T00:38:35Z")

</div>

> [@tera](#):
>
> ```swift
> // Workaround #3
> let elements3: [String: String] = [
> "foo": foo,
> "bar": bar,
> "baz": baz
> ].compactMapValues { $0 }
> 
> ```

This is what I use. I feel like it's concise enough not to require more refinement. You can have a `nil` value, `let` and be explicit in one go.
