2017-05-07 33 views
0

如何將相關類型約束爲協議。如何將相關類型約束爲協議

可以說我有以下的協議和實現它的類:

public protocol TestProtocol { 
    associatedtype TestType 
} 

public class TestClass<T : NSCoding> : TestProtocol { 

    public typealias TestType = T 

    public func get<T>(_ identifier: String) throws -> T? { 
     return "Test" as? T 
    } 
} 

現在一切都很好。 func get會編譯,因爲編譯器知道我的相關類型是這種情況下的協議。

的問題開始與這個用例:

public protocol TestProtocol { 
    associatedtype TestType 

    func get<T>(_ identifier: String) throws -> T? where T : TestType 
} 

public class TestClass<T : NSCoding> : TestProtocol { 

    public typealias TestType = T 

    public func get<T>(_ identifier: String) throws -> T? { 
     return "Test" as? T 
    } 
} 

這不會編譯,因爲編譯器不知道,如果TestType是在這種情況下,ProtocolType。

(它說:「類型‘T’限制到非協議類型‘TestType’」)

我怎樣才能執行accociated類型「TestType」議定書中是一個協議類型?

編輯:我的第一個例子是有點誤導的我想要達到更好的定義如下

public protocol TestProtocol { 
    associatedtype TestType 

    func get<T>(_ identifier: String) throws -> U? where U : TestType 
} 

public class TestClass<T : NSCoding> : TestProtocol { 

    public typealias TestType = T 

    public func get<U>(_ identifier: String) throws -> U? where U : T{ 
     return "Test" as? U 
    } 
} 

我想要的「獲取」返回類型是U型的,實施協議T(我想用它從我的持久存儲中檢索數據)。

問題在於這種表示法不強制T是協議類型(這會導致編譯器錯誤)。我怎麼能執行這個?

第二編輯:

我看問題的時間越長,我是舒爾斯威夫特建議SE-0142是解決這個問題(和迅速的4功能)。

https://github.com/apple/swift-evolution/blob/master/proposals/0142-associated-types-constraints.md

但是,如果你有其他的想法如何實現所需的行爲,只是讓我知道了;)

+0

爲什麼你不只是做'FUNC在協議中得到(_ identifier:String)throws - > TestType?'在類定義中,您將「TestType」設置爲「T」,因此不需要在協議定義中執行「T:TestType」。 – sbarow

+0

是的,你是正確的功能不應該包含T ...我會修改第一篇文章... –

+0

只需看看在第一篇文章。 –

回答

0

由於sbarow建議:

public protocol TestProtocol { 

    associatedtype TestType:Protocol 

    func get<TestType>(_ identifier: String) throws -> TestType? 
} 
+0

對不起,這是一個糟糕的例子,get的返回類型應該是實現TestType協議的其他類型。 –

相關問題