Default value for optional generic parameter in Swift function

前端 未结 1 1198
执笔经年
执笔经年 2020-12-03 17:20

Is it possible to give an optional generic parameter a default value?

I\'m trying to do something like this:

func addChannel(name: String, d         


        
相关标签:
1条回答
  • 2020-12-03 18:18

    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).

    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.

    With Channel<T> you can just use a default, but you'd have to provide the type:

    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.

    (UPDATE ~ Swift 5.2)

    Sometimes you'd like a default type for T. You can do that with an overload. For example, you might want the default type to be Never. In that case, you would add an overload like this:

    func addChannel<T>(name: String, data: T? = nil) -> Channel<T> { ... }
    func addChannel(name: String) -> Channel<Never> { 
        addChannel(name: name, data: Optional<Never>.none)
    }
    

    With that, you can have a simpler call:

    let myChannel = addChannel(name: "myChannelName") // Channel<Never>
    
    0 讨论(0)
提交回复
热议问题