问题
I want to extend dictionary and constrain it to specific key type of NSDate with values of type Array<MyClass>
MyClass is a swift class with no subclass.
extension Dictionary where Key: NSDate, Value: Array<MyClass>{
func myFunction() -> Int{
// Some thing useful
}
}
The above code returns a build error:
Type 'Value' constrained to non-protocol type 'Array'
Ok so it seems that it needs to be constrained to a specific protocol, but strangely enough when I constrain Value to:
extension Dictionary where Key: NSDate, Value: MyClass
The compiler does not complain and the build succeeds. But MyClass is not a protocol. So what gives?
I've managed to constrain it like this:
extension Dictionary where Key: NSDate, Value: CollectionType, Value.Generator.Element: MyClass{
func myFunction() -> Int{
var count = 0
for (_, graphicItemArray) in self{
count+= (graphicItemArray as! [MyClass]).count
}
return count
}
}
But this requires a forced cast because I need to get the count property in a Integer form.
So why can't I constrain it explicitly to value type of [MyClass] ?
回答1:
Not being able to use a where
clause with a struct may be an error. Checking the language reference for where clauses and following into
conformance-requirement → type-identifier | ...
Seems like type-identifier should accept a struct
, even the example they use is Int
.
This maybe be something to file a bug for.
Related to your specific problem, it seems to work if you use _ArrayType which is a protocol that Array
implements and has the methods you need.
extension Dictionary where Key: NSDate, Value: _ArrayType ...
I am not sure tho if using that kind of internal protocols would flag your app and make it fail Apple review.
来源:https://stackoverflow.com/questions/32815718/extending-dictionary-with-key-and-value-constraints