考虑以下:
struct SomeStruct {}
var foo: Any!
let bar: SomeStruct = SomeStruct()
foo = bar // Compiles as expected
var fooArray: [Any] = []
let barArray: [SomeStruct] = []
fooArray = barArray // Does not compile; Cannot assign value of type '[SomeStruct]' to type '[Any]'
Run Code Online (Sandbox Code Playgroud)
我一直试图找到这背后的逻辑,但没有运气.值得一提的是,如果将结构更改为类,则可以完美地运行.
总是可以添加一个变通方法并映射fooArray的每个对象并将它们转换为Any类型,但这不是问题.我正在寻找一个解释为什么这样做的样子.
有人可以解释一下吗?
为什么Swift不允许我为Foo<U>类型的变量赋值Foo<T>,其中U是T的子类?
例如:
class Cheese {
let smell: Int
let hardness: Int
let name: String
init(smell: Int, hardness: Int, name: String) {
self.smell = smell
self.hardness = hardness
self.name = name
}
func cut() {
print("Peeyoo!")
}
}
class Gouda: Cheese {
let aged: Bool
init(smell: Int, hardness: Int, name: String, aged: Bool) {
self.aged = aged
super.init(smell: smell, hardness: hardness, name: name)
}
override func cut() {
print("Smells delicious")
}
}
class Platter<Food> {
var food: …Run Code Online (Sandbox Code Playgroud) 我想在类型为[String:SomeClass]的Dictionary中存储一个更专业的类型.下面是一些说明我的问题的示例代码(也可以在https://swiftlang.ng.bluemix.net/#/repl/579756cf9966ba6275fc794a上进行):
class Thing<T> {}
protocol Flavor {}
class Vanilla: Flavor {}
var dict = [String:Thing<Flavor>]()
dict["foo"] = Thing<Vanilla>()
Run Code Online (Sandbox Code Playgroud)
它会产生错误ERROR at line 9, col 28: cannot assign value of type 'Thing<Vanilla>' to type 'Thing<Any>?'.
我已经尝试过铸造,Thing<Vanilla>() as Thing<Flavor>但这会产生错误cannot convert value of type 'Thing<Vanilla>' to type 'Thing<Flavor>' in coercion.
我也尝试将Dictionary定义为类型,[String:Thing<Any>]但也不会改变任何东西.
如何在Thing不诉诸普通的情况下创建不同s 的集合[String:AnyObject]?
我还应该提一下,Thing我没有定义类(实际上它是关于BoltsSwift Task的),因此创建Thing没有类型参数的基类的解决方案不起作用.
在Swift中考虑以下内容:
struct GenericStruct<T> {}
class A {}
class B: A {}
func doSomething() -> GenericStruct<A> {
return GenericStruct<B>()
}
Run Code Online (Sandbox Code Playgroud)
这给出了错误:
无法将返回表达式转换
GenericStruct<B>为返回类型GenericStruct<A>
但是B是它的子类A.
GenericStruct<B>为GenericStruct<A>?我只是好奇是否可以做如下的事情
protocol Data { }
class A: Data { }
class B: Data { }
class Generic<T> { }
class doStuff {
func prepareToDoStuff() {
self.doTheStuffWithGenerics([Generic<A>(), Generic<B>])
}
func doTheStuffWithGenerics<T: Generic<Data>>(_ generics: [T]) {
}
}
Run Code Online (Sandbox Code Playgroud)
目前我的编译器告诉我没有说
“无法将类型‘Generic[A]’的值转换为预期元素类型‘Generic[Data]’”
有什么想法吗?解决方案?