swift - 在 Swift 中将协议(protocol)实现者升级为协议(protocol)的通用方法

标签 swift generics

我想编写一个方法来将实现协议(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/

相关文章:

ios - 如何截取屏幕截图并裁剪掉空白区域?

java - 泛型和 instanceof - java

java - 使用泛型类型中的 super 将 Map 流式传输到 Consumer 后使用 orElse 编译错误

java - 将 int[][] 作为通用参数传递

c# - 如何使用没有约束的类型参数调用具有泛型约束的方法?

generics - F# 中下划线泛型的作用是什么

swift - 显示 JSON 中的动态 GoogleMap 标记

ios - swift框架中使用modulemap桥接OC,project中报缺少所需模块

ios - 如何让你的推送通知打开某个 View Controller ?

ios - 如果我通知操作已完成,我应该使用 PublishSubject 吗?