我有一个协议CustomObject
,并且为String
添加了扩展以符合CustomObject
。我还为Array
(如果Element
转换为CustomObject
和Dictionary
(如果键和值符合CustomObject
)添加了条件一致性。但是,当我尝试将包含String和CustomObject
的数组分配给CustomObject
变量(或作为参数传递时,编译器会抱怨为Value of type '[CustomObject]' does not conform to specified type 'CustomObject'
在条件符合数组的情况下,如果元素为CustomObject
,则数组也应为CustomObject
。
这缺少什么?
尝试的代码:
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'`
更新:
如果我将数组扩展名更改为extension Array: CustomObject where Element == CustomObject
,则该错误将消失,并出现另一个错误。
let dict2: CustomObject = ["key2": dict1]//Contextual type 'CustomObject' cannot be used with dictionary literal