我想编写一个方法来将实现协议(protocol)的对象向上转换为其协议(protocol)。
例如,假设我们有一个协议(protocol) Drawable
和一个实现它的结构(或类)Shape
。
protocol Drawable {}
struct Shape: Drawable {}
我想要一个不可失败的向上转换,例如:
let shape = Shape()
let drawable: Drawable = upcast(shape)
到目前为止,我最接近的解决方案如下。但是,我不知道如何指定 T
实现 U
因此结果/类型转换不需要是可选的/可失败的。
func upcast<T, U>(object: T) -> U? {
return object as? U
}
所以我可以这样做:
let shape = Shape()
let drawable: Drawable? = upcast(shape)
所有这一切的重点是我希望能够做到这一点:
let shapes = [shape]
let drawables: [Drawable] = shapes
是否可以编写一个通用方法来表示 T
实现 U
,因为 U 是一个协议(protocol)?
最佳答案
你可以试试这样的:
// This is your function
func upcast<T, U>(instance: T) -> U? {
return instance as? U
}
// This is what you can use to upcast sequence into an array
func flatUpcast<S: SequenceType, T, U where S.Generator.Element == T>(sequence: S) -> [U] {
return sequence.flatMap() {
upcast($0)
}
}
// Playground try-out
protocol Drawable { }
struct Shape: Drawable { }
let shape = Shape()
let shapes = [shape, shape, shape]
let drawables: [Drawable] = flatUpcast(shapes)
关于swift - 在 Swift 中将协议(protocol)实现者升级为协议(protocol)的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33454740/