2016-09-17 3 views
0

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? 
} 

을, 나는 이런 식으로 선언하여 스위프트 2에서이 작업을 수행 할 수 있었다 :

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

그러나 상기 (스위프트 3에서 작동하지 않습니다 이 컴파일러 충돌)이 작품처럼

답변

0

그것은 같습니다.

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 
} 
관련 문제