2

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>'

niklassaers
  • 8,480
  • 20
  • 99
  • 146

1 Answers1

5

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()

Casey
  • 6,531
  • 24
  • 43
  • Perhaps worth mentioning that `let foo = Optional(["asdf":123])` will not have access to `.doSomething`, as `foo` will be of type `Optional>`, and since `Int` is a value type, it does not conform to `AnyObject`. On the other hand, `let foo : [String:AnyObject]? = Optional(["asdf":123])` _will_ have access to `.doSomething()` (and this is the implicit type use in your example above), where the `Value` of this single entry will be of type `__NSCFNumber` (obj-c/foundation _class_ type). – dfrib Feb 17 '16 at 10:42
  • @dfri you are right, if you import Foundation, otherwise there is no such a bridge (so, that is fine and expected) – user3441734 Feb 17 '16 at 10:50