I've tried the solution in extension of Dictionary where <String, AnyObject> but it won't compile for me.
I simply want to constrain a dictionary extension to struct
types. Is there any way of accomplishing this?
import Cocoa
struct Foo: Hashable {
let bar: String
static let predefinedFoo = Foo(bar: "something")
var hashValue: Int { return bar.hashValue }
public static func ==(lhs: Foo, rhs: Foo) -> Bool {
return lhs.hashValue == rhs.hashValue
}
}
struct Baz {
let isSpecial: Bool
}
extension Dictionary where Key: Foo, Value: Baz { // Note that the == syntax does not compile, either
var hasSpecialPredefined: Bool {
return self[.predefinedFoo]?.isSpecial ?? false
}
}
let test: [Foo: Baz] = [.predefinedFoo: Baz(isSpecial: true)]
test.hasSpecialPredefined
With the above code, I get two compile errors:
error: type 'Key' constrained to non-protocol type 'Foo'
error: type 'Value' constrained to non-protocol type 'Baz'
error: '[Foo : Baz]' is not convertible to '<<error type>>'
test.hasSpecialPredefined
^~~~
Is it possible to constrain an extension by a struct? If not, why not? This seems perfectly reasonable.
Note that
Foo
andBar
, here, are not under my control. They represent structs that are defined in an external module, and the dictionary I want to extend also comes from this module. Answers should assumeFoo
will always be astruct
, and that struct willalways
be the key type for the dictionary.