Search code examples
iosswiftdictionaryswift2anyobject

Extending Optional<Dictionary<String, AnyObject>>


I would like to make an extension on Optional<Dictionary<String, AnyObject>>. How can I write this?

I was expecting it to be something like

extension Optional where 
Wrapped : Dictionary,
Key : String,
Value : AnyObject { ... }

but it wants Dictionary to take the parameters directly, and even if this worked I expect it would complain that String was not a protocol. So I try

extension Optional where Wrapped : Dictionary<String, AnyObject> { ... }

but here it complains that type 'Wrapped' constrained to non-protocol type 'Dictionary<String, AnyObject>'


Solution

  • use dot syntax to access the Key and Value of Wrapped.

    extension Optional where Wrapped: DictionaryLiteralConvertible, Wrapped.Key: StringLiteralConvertible, Wrapped.Value: AnyObject {
        func doSomething() {
            print("did it")
        }
    }
    

    now you can call this: Optional(["asdf":123]).doSomething()

    but not this: Optional([123:123]).doSomething()