[swift-evolution] 100% bikeshed topic: DictionaryLiteral

Charles Constant charles at charlesism.com
Tue Jan 9 22:26:50 CST 2018


Hi Nevin (et al)

Here's the relevant section of my code. It's from a protocol I use called
"ParameterSet" to extend OptionSets to contain small numbers (like an Enum
with an associated type, but all the data is stored in the UInt). Wouldn't
be my first choice to share, as it breaks KISS. Anyhow, the
"ExpressibleByDictionaryLiteral" lets me specify a "params" template
tersely. I only found out how to use the -Literal initializers last year. I
love them.

struct DrumNote: ParameterSet {
let rawValue: UInt

static let params: [ParamType] = [ ["velocity":0...255], "flam", "roll",
"reverse" ]

static let
velocity = param(0),
flam = param(1),
roll = param(2),
reverse = param(3),

// ...

}

enum ParamType: ExpressibleByStringLiteral, ExpressibleByDictionaryLiteral {
public init( dictionaryLiteral elements: (String,Any)... ) {
if let pair = elements.first as? (String,ClosedRange<FloatLiteralType>) {
self = .doub(pair.0,pair.1) }
else if let pair = elements.first as?
(String,CountableClosedRange<IntegerLiteralType>) { self = .int(pair.0,
pair.1.lowerBound ... pair.1.upperBound ) }
else { fatalError("Can only init from Double...Double or Int...Int") }
}

// ...
}


On Tue, Jan 9, 2018 at 6:10 PM, Nevin Brackett-Rozinsky <
nevin.brackettrozinsky at gmail.com> wrote:

> On Tue, Jan 9, 2018 at 7:47 PM, charles at charlesism.com <
> charlesism.com at gmail.com> wrote:
>
>> I used a DictionaryLiteral only yesterday, and it turned what would have
>> a typically unreadable array of Structs into something much more elegant.
>> I'm pretty sure the only reason Literals (of all varieties) aren't used
>> more often is because Swift programmers don't realize they are available
>> and easy to implement.
>>
>
> Could you provide an example of how you used DictionaryLiteral?
>
> Nevin
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20180109/89eac32f/attachment.html>


More information about the swift-evolution mailing list