【发布时间】:2015-08-08 16:21:56
【问题描述】:
我正在尝试使用具有关联类型的协议作为类 func 的返回值。
Another post here on stackoverflow 是关于同一个问题,根据这篇文章的回答,我尝试了以下方法:
// addArg takes a single Int argument and returns something,
// which is capable of adding a another Int argument
class OpWithNoArg {
func addArg<OP: OpWithOneArg where OP.ArgType == Int>(arg: Int) -> OP {
return OpWithOneArgImpl() // (1) error here !
}
}
// a protocol with associated type, which allows adding another
// argument of a not yet specified type
protocol OpWithOneArg {
typealias ArgType
func addAnotherArg(arg: ArgType)
}
// an implementation of the protocol above,
// which fixes the associated type to an Int
class OpWithOneArgImpl : OpWithOneArg {
typealias ArgType = Int
func addAnotherArg(arg: Int) {
// ...
}
}
Xcode 7.0 Beta 4 中标有 (1) 的行的错误是
无法将“OpWithOneArgImpl”类型的返回表达式转换为 预期返回类型“OP”
如果我将返回值更改为可选并返回nil,则示例编译成功:
// return null
class OpWithNoArg {
func addArg<OP: OpWithOneArg where OP.ArgType == Int>(arg: Int) -> OP? {
// return OpWithOneArgImpl()
return nil
}
}
这种使用关联类型的协议作为返回值的方式是否可以在swift中使用,如果是这种情况,如何修复上面提到的编译器错误?
提前致谢!
编辑:
在 Java 中,代码类似于以下 sn-p。我试图在 Swift 中找到一种方法来实现同样的目标。
class C {
<T> P<T> f(T arg) {
return new PImpl();
}
}
interface P<S> {
void g(S arg);
}
class PImpl<S> implements P<S> {
PImpl() {}
public void g(S arg) {}
}
【问题讨论】:
-
见stackoverflow.com/a/27406808。基本上,
OP不是“OpWithOneArg类型为Int”,而是在调用它时使用的任何结果。这种类型可能无法从OpWithOneArgImpl转换,所以它不允许你。 -
您的链接包含一个非常有用的解释!像我这样有大量 Java 背景的人必读;)