gpt4 book ai didi

swift - 如何存储通用闭包?

转载 作者:行者123 更新时间:2023-11-30 13:04:34 25 4
gpt4 key购买 nike

我正在尝试使用 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com