Reputation: 53
The program compiles with no warnings and runs as expected, despite all the generics used (not shown).
However, when I try to clean it up by removing the notUsed
method from the protocol, I get the compiler error in the subject, and unlike similar questions, there is no reference to any class or method in the long stack dump from the compiler. Also, above the editor, the message:
"An internal error occurred. Source editor functionality is limited. Attempting to restore...." appears immediately.
It is simplified and therefore, hypothetical, so please don't ask what am I trying to achieve by casting to type T in the parse function. Here is the entire, osx command line program, that runs perfectly fine as shown. Is it not supposed to? If you have a suggestion, could you please provide the code as well, since the generics syntax is a bit tricky for me to get.
public class Future<T> {
init(_ v:T) { value = v }
let value: T
}
protocol DataParserType {
associatedtype ResultType
func notUsed(with data:Data) -> ResultType
func parse<ResultType>(with data:Data) -> Future<ResultType>
}
class JSONParser: DataParserType {
func notUsed(with data:Data) -> Future<Any> { return Future(2.0) }
func parse<T>(with data:Data) -> Future<T> { return Future(45 as! T) }
}
let X: Future<Int> = JSONParser().parse(with: Data())
print(X.value)
Upvotes: 1
Views: 279
Reputation: 53
I still haven't figured out why it was working the way it was, but here is how it should look like; the Generic argument needs to be part of the class signature, rather than the function signature.
class JSONParser<FutureValue>: DataParserType {
typealias ResultType = FutureValue
func parse(with data:Data) -> Future<FutureValue> { return Future(45 as! FutureValue) }
}
Upvotes: 0
Reputation: 1234
I managed to reproduce your problem, assuming that parse
in your example was supposed to be inside the JSONParser
class.
For the generic function to satisfy the protocol, the protocol must also declare it as generic. However, just putting <T>
in the declaration will not solve the problem, as it needs to be used somewhere in the function signature. The associated types will not help with this.
Your options are:
Change the parse
function signature in the protocol to be generic, and use T
somewhere in the arguments.
Don't use a generic function.
One day Apple will learn the difference between compilation error and segmentation fault, but today is not that day.
Upvotes: 1