Today, the group participants Someone made such a problem,Why use the characteristic dictionary type as a generic type constraint,It will inevitably error?
1 |
inheritance from non-protocol, non-class type 'Dictionary<String, Any>' |
Obviously,He said very clearly,"You can not be from a non-agreement、Non-type class inheritance. "。Obviously,The dictionary is a generic structure...
Then the solution is also very clear ideas,Creating a class to decorate a dictionary might be a good choice but too much trouble,Then start from the agreement。
Conditional agreement to follow
We can extend this structure to the dictionary,Let us follow a protocol of empty:
1 |
protocol targetDictionaryType {} |
But here we note qualification,That dictionary Key must be a String:
1 |
extension Dictionary :targetDictionaryType where Key == String {} |
All content is empty,Because without doing any extra work。
Such,We can use this protocol to constrain,If the type of dictionary does not meet the requirements,Then the dictionary will not abide by our agreement:
1 2 3 |
func test<T:targetDictionaryType>(dict:T) { ... } |
Test Results
1 2 3 4 |
let d = ["":1] test(dict: d) //正常工作 |
1 2 3 4 5 |
let a = [1:1] test(dict: a) //error: cannot invoke 'test(dict:)' with an argument list of type '(dict: [Int : Int])' |
Original article written by LogStudio:R0uter's Blog » How to use dictionary types as generic constraints in Swift
Reproduced Please keep the source and description link:https://www.logcg.com/archives/3101.html
Paradigm =?Generics
There is no unification by this,It is generic!
It's changed~