Home

Awesome

DictionaryLiteralShorthand

DictionaryLiteralShorthand is a Swift compiler plugin that provides a macro for creating dictionary literals with keys as string representations of corresponding variable names.

It simplifies the process of creating dictionaries by automatically generating the keys based on variable names.

This macro is inspired by the shorthand syntax for object initializers in JavaScript.

UIKit also offers a similar macro called NSDictionaryOfVariableBindings for NSDictionary.

Usage

In the past, if you want to define a dictionary with the key is the same as the variable name, you write:

let a = 99
let b = "foo"
let dictionary: [AnyHashable: Any] = ["a": a, "b": b]

With this macro, you simply write

import DictionaryLiteralShorthand

let a = 99
let b = "foo"
let dictionary: [AnyHashable: Any] = #dict(a, b)

// This is the equalivant code generated by the compiler:
// let dictionary: [AnyHashable: Any] = ["a": a, "b": b]

The compiler magically "exapnds" the macro for you, saving your time from writing boilerplate code.

Note:

/// ❌ This raises a compiler error, as we don't have a "variable name" to input to dictionary
let dictionary: [AnyHashable: Any] = #dict(["Foo", 999])

Installation

Swift Package manager

Open your project with Xcode, go

After installation, Xcode might ask you if you want to enable DictionaryLiteralShorthandMacros, select Trust & Enable

Requirements

Resources

ToDo

License

DictionaryLiteralShorthand is released under the MIT license. See LICENSE for details.