I have a protocol CustomObject
, and I added extention for String
to conform to CustomObject
. I also added conditional conformance to Array
(if Element
confroms to CustomObject
) and Dictionary
(if key and value conforms to CustomObject
). But when I try to assign an array that contains String and CustomObject
to CustomObject
variable(or pass as an argument, the compiler complaints as Value of type '[CustomObject]' does not conform to specified type 'CustomObject'
With conditional conformance of array, it the element is CustomObject
, the array should also be CustomObject
.
What is missing in this?
Code tried:
protocol CustomObject {
var value: String { get }
}
extension String: CustomObject {
var value: String {
return self
}
}
extension Array: CustomObject where Element: CustomObject {
var value: String {
return "{\n\(self.map{$0.value}.joined(separator: "\n"))\n}"
}
}
extension Dictionary: CustomObject where Key: CustomObject, Value: CustomObject {
var value: String {
return self.map {
return "\($0.value){\n\($1.value)\n}"
}
.joined(separator: "\n")
}
}
var params = [
"v1",
"v2",
]
let dict1 = ["key1": params]
let dict2: CustomObject = ["key2": dict1]
let array1: CustomObject = ["key3", dict2.value]// Error here `Value of type '[CustomObject]' does not conform to specified type 'CustomObject'`
func doSomething(_ object: CustomObject) {
//...
print("value -- " + object.value)
}
let array2 = ["key3", dict2]
doSomething(array2)// Here also `Value of type '[CustomObject]' does not conform to specified type 'CustomObject'`
UPDATE:
If I change array extension to extension Array: CustomObject where Element == CustomObject
This error goes away and another error comes in.
let dict2: CustomObject = ["key2": dict1]//Contextual type 'CustomObject' cannot be used with dictionary literal