0

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
Johnykutty
  • 12,091
  • 13
  • 59
  • 100
  • The problem is that `dict2` has the type `CustomObject` and that does not *conform* to `CustomObject`. As a consequence, `array2` does not (conditionally) conform to it either. – Martin R Jun 18 '19 at 09:49
  • Okay.. as per my edit, first error goes away. Is it possible to conform a dictionary to `CustomObject`? – Johnykutty Jun 18 '19 at 10:36
  • 1
    Unless I am mistaken, using a “type eraser” `struct AnyCustomObject: CustomObject { ... }` as described in linked-to Q&A is currently the only solution. Then `let array2 = [AnyCustomObject("key3"), AnyCustomObject(dict2)] ; doSomething(array2)` should work. – Martin R Jun 18 '19 at 11:05

0 Answers0