Is it possible to give an optional generic parameter a default value?
是否可以为可选的通用参数提供默认值?
I'm trying to do something like this:
我正在尝试做这样的事情:
func addChannel<T>(name: String, data: T? = nil) -> Channel {
}
let myChannel = addChannel("myChannelName")
But I'm getting an error saying
但是我说错了
Argument for generic parameter 'T' could not be inferred
无法推断出泛型参数“T”的参数
Is it just a case of what I'm trying to do being impossible?
这只是我想要做的事情的一个例子吗?
1 个解决方案
#1
6
It's impossible in the way you've done it. Given just the code above, what type is T
? The compiler, as it says, can't figure it out (neither can I, and I assume you couldn't either because the data's not there).
你完成它的方式是不可能的。只给出上面的代码,T是什么类型的?正如它所说的那样,编译器无法弄明白(我也不能,而且我认为你也不能,因为数据不存在)。
The solution to the specific question is to overload rather than use defaults:
特定问题的解决方案是重载而不是使用默认值:
func addChannel<T>(name: String, data: T?) -> Channel { ... }
func addChannel(name: String) -> Channel { ... }
let myChannel = addChannel("myChannelName")
But it raises the question of what you're doing here. You would think that Channel
should be Channel<T>
. Otherwise, what are you doing with data
? Without resorting to Any
(which you should strongly avoid), it's hard to see how your function can do anything but ignore data
.
但它提出了你在这里做什么的问题。你会认为Channel应该是Channel
With Channel<T>
you can just use a default, but you'd have to provide the type:
使用Channel
func addChannel<T>(name: String, data: T? = nil) -> Channel<T> { ... }
let myChannel: Channel<Int> = addChannel("myChannelName")
Otherwise the compiler wouldn't know what kind of channel you're making.
否则,编译器不会知道您正在制作什么类型的频道。
#1
6
It's impossible in the way you've done it. Given just the code above, what type is T
? The compiler, as it says, can't figure it out (neither can I, and I assume you couldn't either because the data's not there).
你完成它的方式是不可能的。只给出上面的代码,T是什么类型的?正如它所说的那样,编译器无法弄明白(我也不能,而且我认为你也不能,因为数据不存在)。
The solution to the specific question is to overload rather than use defaults:
特定问题的解决方案是重载而不是使用默认值:
func addChannel<T>(name: String, data: T?) -> Channel { ... }
func addChannel(name: String) -> Channel { ... }
let myChannel = addChannel("myChannelName")
But it raises the question of what you're doing here. You would think that Channel
should be Channel<T>
. Otherwise, what are you doing with data
? Without resorting to Any
(which you should strongly avoid), it's hard to see how your function can do anything but ignore data
.
但它提出了你在这里做什么的问题。你会认为Channel应该是Channel
With Channel<T>
you can just use a default, but you'd have to provide the type:
使用Channel
func addChannel<T>(name: String, data: T? = nil) -> Channel<T> { ... }
let myChannel: Channel<Int> = addChannel("myChannelName")
Otherwise the compiler wouldn't know what kind of channel you're making.
否则,编译器不会知道您正在制作什么类型的频道。