Swift generics with default value
<p>I'm trying to implement some single solution for each callbacks in application. So I want any callback use the same class, or at least family of classes.</p>

<ul>
<li>Every callback can be successful or not. </li>
<li>If it is successful, it can
contain some result of operation.</li>
<li>If it is not, it can contain information about what it is failed.</li>
</ul>

<p>The common callbacks usage looks like this:</p>

<pre><code>func foo(callback: ((success: Bool, result: Result?, error: Error?) -&gt; Void)?) { }
</code></pre>

<p>Or: </p>

<pre><code>func foo(success: ((result: Result) -&gt; Void)?, failure: ((error: Error) -&gt; Void)?) { }
</code></pre>

<p>I don't like any of them. I want to have single elegant solution for each callback. I found something similar in <a href="https://github.com/Alamofire/Alamofire" rel="nofollow">Alamofire</a> library.</p>

<pre><code>    enum CallbackResult&lt;T, V&gt; {
        case success(value: T?)
        case failure(error: V?)

        var isSuccess: Bool {

            switch self {
            case .success: return true
            case .failure: return false
            }
        }
    }

    func foo(callback: ((result: CallbackResult&lt;Any, AnyObject&gt;) -&gt; Void)?) {
         callback?(result: .success(value: nil))
    }
</code></pre>

<p>This solution it nice. But like in my example, not always we need to pass any value or error as a parameter. Anyway, compiler always need to know what type generic parameters should be of. So even if I don't meter what type value is, I always should put there at least <code>Any</code> or <code>AnyObject</code> . It is overcomplicated. </p>

<p>I've tried to change it with class solution:</p>

<pre><code>    class CallbackResult&lt;T, V&gt; {

        let isSuccess: Bool

        let value: T?

        let error: V?

        fileprivate init(success: Bool, value: T? = nil, error: V? = nil) {

            self.isSuccess  = success
            self.value      = value
            self.error      = error
        }

        static func success(value: T? = nil) -&gt; CallbackResult {
            return CallbackResult(success: true, value: value)
        }

        static func failure(error: V? = nil) -&gt; CallbackResult {
            return CallbackResult(success: false, error: error)
        }
    }

    func foo(callback: ((result: CallbackResult&lt;Any, AnyObject&gt;) -&gt; Void)?) {
         callback?(result: CallbackResult.success(value: nil))
    }
</code></pre>

<p>It has the same functionality. But even in this way it didn't solve my problem. You can't just write like this:</p>

<pre><code>CallbackResult&lt;_, Error&gt;
</code></pre>

<p>It will not work.</p>

<p>Maybe somebody know solution to my problem? Some way to put default value maybe^ not to write <code>Any</code> each time? Or for now there is only ugly way of using that approach?</p>