我有一个非常简单的游乐场:
protocol MyProtocol {}
struct MyType: MyProtocol {}
class MyClass <T: MyProtocol> {
func myFunction(array: [T]) {
if let myArray = array as? [MyType] {
println("Double!")
}
}
}
let instance = MyClass<MyType>()
let array = [MyType(), MyType()]
instance.myFunction(array)
Run Code Online (Sandbox Code Playgroud)
然后它说" MyType is not a subtype of 'T'"就if let行了.嗯,我想,但是,MyType和T兼容.
当我修改if let语句时,它实际上有效:
if let first = array.first as? MyType
Run Code Online (Sandbox Code Playgroud)
但是现在我不能投array来[MyType](当然,我知道这是斯威夫特的静态类型规范.)
我想知道问题是什么.我对泛型的理解?或者是Swift语言的限制?如果是这样,有没有办法这样做?
提前致谢.
Swift 没有\xe2\x80\x99t 的内置行为来推测将数组\xe2\x80\x99s 内容从一种任意类型转换为另一种类型。它只会对它知道具有子类型/超类型关系的两种类型执行此操作:
\n\nclass A { }\nclass B: A { }\nlet a: [A] = [B(),B()]\n// this is allowed - B is a subtype of A\nlet b = a as? [B]\n\nlet a: [AnyObject] = [1,2,3]\n// this is allowed - NSNumber is a subtype of AnyObject\nlet b = a as? [NSNumber]\n\nstruct S1 { }\nstruct S2 { }\n\nlet a = [S1(),S1()]\n// no dice - S2 is not a subtype of S1\nlet b = a as? [S2]\nRun Code Online (Sandbox Code Playgroud)\n\n该协议对\xe2\x80\x99 没有帮助:
\n\nprotocol P { }\nstruct S1: P { }\nstruct S2: P { }\n\nlet a = [S1(),S1()]\n// still no good \xe2\x80\x93 just because S1 and S2 both conform to P\n// doesn\xe2\x80\x99t mean S2 is a subtype of S1\nlet b = a as? [S2]\nRun Code Online (Sandbox Code Playgroud)\n\n您的示例基本上是最后一个示例的变体。您有一个类型为 的数组[T],并且希望将其转换为[MyType]. 重要的是要了解您没有类型的数组[MyProtocol]。您的泛型类型T是一种特定类型,它必须实现MyProtocol,但 \xe2\x80\x99s 不是同一件事。
要了解为什么\xe2\x80\x99t 不能从任何类型强制转换为任何其他类型,请尝试以下代码:
\n\nprotocol P { }\nstruct S: P { }\n\nlet a: [P] = [S(),S()]\nlet b = a as? [S]\nRun Code Online (Sandbox Code Playgroud)\n\n这将生成一个运行时错误:“致命错误:不能在不同大小的类型之间进行 unsafeBitCast”。这暗示了为什么只能将包含一种引用类型的数组转换为子类型 \xe2\x80\x93 it\xe2\x80\x99s,因为所发生的只是从一种指针类型到另一种指针类型的位转换。这适用于超/子类型类,但不适用于任意类、结构或协议,因为它们具有不同的二进制表示形式。
\n| 归档时间: |
|
| 查看次数: |
597 次 |
| 最近记录: |