想知道为什么这是不可能的:
class Test<T, U> {
init(key: T, value: U) {
}
}
let array: [Test<String, Any>] = [
Test<String, Double>(key: "test", value: 42),
Test<String, Array>(key: "test", value: [])
]
我遇到了一个错误:
错误:无法将类型为“Test”的值转换为预期的元素类型“Test”
更新:根据Brduca的回答
为什么这个可以工作:
class Test<T, U> {
let key: T
let value: U
init(key: T, value: U) {
self.key = key
self.value = value
}
}
let properties: [Test<String, Any>] = [
Test(key: "fontSize", value: []),
Test(key: "textColor", value: 42)
]
但这个不行:
class TestBlock<T, U> {
let key: String
let block: (T, U) -> Void
init(key: String, block: @escaping (T, U) -> Void) {
self.key = key
self.block = block
}
}
let block1: (UILabel, CGFloat) -> Void = {
$0.font = $0.font.withSize($1)
}
let block2: (UILabel, UIColor) -> Void = {
$0.textColor = $1
}
let propertiesWithBlock: [TestBlock<UILabel, Any>] = [
TestBlock(key: "fontSize", block: block1),
TestBlock(key: "textColor", block: block2)
]
I'm getting this error:
Cannot convert value of type 'TestBlock<UILabel, CGFloat>' to expected element type 'TestBlock<UILabel, Any>'
Test<String, Double>
不是Test<String, Any>
的子类型。 - Sulthan