[swift-evolution] Swift Generic Subtype Problem

Cao Jiannan frogcjn at 163.com
Tue Feb 16 02:45:46 CST 2016


Hi Slava:

> class B : A {}
> 
> class C : P {
> 	func f() -> B {} // compile error
> }
> 
> Once witness matching supports variance, your example will work.
> 
> But a better way would be to use an associated type:
> 
> protocol SequeHandlerType {
>     associatedtype View : UITableView
>     var tableView: View! { get }
> }


Yes. This makes sense to me. 
Associate type is a hard toy for me. 
Sometimes I can figure out, sometimes I cannot. Sometimes I figure out but compiler say no.

The problem is not really with the optional sub typing relation, but looks like.
AssociatedType can solve the problem like this:

class A {}

class B : A {}


protocol HandlerType{
    var a: A { get }
}

class Handler: HandlerType{
    var b = B() //Compiler Error, though b is subtype of A
}

should be:

protocol HandlerType{
    typealias Target :A
    var a: Target { get }
}

class Handler: HandlerType {
    var a = B()
}

This is the solution to my question.
Thanks.

- Jiannan




-------------- next part --------------
An HTML attachment was scrubbed...
URL: <https://lists.swift.org/pipermail/swift-evolution/attachments/20160216/fa1394bc/attachment.html>


More information about the swift-evolution mailing list