swift - 如何存储通用闭包?

标签 swift

我正在尝试使用 Swift 3 中的闭包创建类型删除类型,但我不知道如何将闭包存储在属性中。如何存放闭包以供以后使用?请参阅下面的代码:

protocol ProtocolA {
    associatedtype AssociatedType
}

protocol ProtocolB {
    associatedtype AssociatedType
    func fn<A: ProtocolA>(a: A) where A.AssociatedType == AssociatedType
}

class AnyProtocolB<T>: ProtocolB {
    typealias AssociatedType = T

    init<A: ProtocolA>(fn: @escaping (A) -> Void)  where A.AssociatedType == AssociatedType {
        _fn = fn
    }

    func fn<A: ProtocolA>(a: A) where A.AssociatedType == AssociatedType {
        _fn(a)
    }

    let _fn: (A) -> Void // how to declare this so it will compile?
}

顺便说一句,我可以在 Swift 2 中通过如下声明来做到这一点:

let _fn: (AnyProtocolA<AssociatedType>) -> Void

但是上面的代码在 Swift 3 中不起作用(它会使编译器崩溃。)

最佳答案

看起来这可行:

protocol ProtocolA {
    associatedtype AssociatedType
}

class AnyProtocolA<T>: ProtocolA {
    typealias AssociatedType = T

    init<A: ProtocolA>(_ a: A) where AssociatedType == A.AssociatedType {

    }
}

protocol ProtocolB {
    associatedtype AssociatedType
    func fn<A: ProtocolA>(a: A) where A.AssociatedType == AssociatedType
}

class AnyProtocolB<T>: ProtocolB {
    typealias AssociatedType = T

    init<A: ProtocolA>(fn: @escaping (A) -> Void)  where A.AssociatedType == AssociatedType {
        _fn = { fn(wrap($0)) }
    }

    func fn<A: ProtocolA>(a: A) where A.AssociatedType == AssociatedType {
        _fn(AnyProtocolA(a))
    }

    let _fn: (AnyProtocolA<T>) -> Void
}

func wrap<A: ProtocolA, T>(_ a: AnyProtocolA<T>) -> A where A.AssociatedType == T {
    return a as! A
}

关于swift - 如何存储通用闭包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39547971/

相关文章:

ios - 在 userdefaults 中保存临时数据?

ios - Swift 优化级别 'Fastest' 中断数组排序

swift - NSPredicate:如何将 CONTAINS 与 NSDate 字段一起使用?

ios - 类型 'inout UIButton' 不符合协议(protocol) 'ReactiveCompatible'

swift - 为什么我可以在没有框架引用的情况下使用 MessageUI?

swift - Firebase 实时数据库查询 Swift 中的两个 child

swift - 'type: Undefined' 会默认为 AnyObject 吗?

swift - KeyedDecodingContainer 解码内部 Decodable 对象

ios - 两个 Storyboard,一个标签栏 Controller

ios - RxSwift - 在 X 秒内未收到元素后发出