説明できないメソッドで問題が発生しました。ここでは、問題を示し、いくつかのテストコードは次のとおりです。同じプロトコルのインスタンスを受け付けないメソッドの型としてスウィフトプロトコルが使用されました
protocol Base {}
protocol Extended: Base {}
struct Instance:Extended {}
let anInstance = Instance()
let instanceOfBase = anInstance as Base
let instanceOfExtended = anInstance as Extended
func aMethod<T:Base>(_ instance:T) {}
aMethod(anInstance)
aMethod(instanceOfBase) // Error - Cannot invoke 'aMethod' with an argument list of type '(Base)'
aMethod(instanceOfExtended) // Error - Cannot invoke 'aMethod' with an argument list of type '(Extended)'
私はなどのプロトコル、ジェネリック、上で読んだのApple DOCOによるaMethod()
Base
プロトコルに準拠する任意のオブジェクトを受け入れる必要があります。それでも、私はそれらをBase
またはExtended
にキャストした両方のインスタンスを拒否します。
誰でもこれを説明できますか?また
:
func aMethod2(_ instance:Base) {}
aMethod2(anInstance)
aMethod2(instanceOfBase)
aMethod2(instanceOfExtended)
作品細かいので、違いがBase
または<T:Base>
に(しゃれを言い訳)instance
引数がベースとされているかどうかのようです。
ここでジェネリックを宣言する理由は誰でも質問してください。
func addViewController<T:ModelObject>(_ stack:inout [UIViewController],
object:T?,
controller:DetailsViewController<T>?,
storyboardId:String) {...
ご覧のとおり、いくつかの引数を同じタイプに制限したいと思います。したがって、単にベースを指定するのではなく、ジェネリックを使用します。
[プロトコルがそれ自体に準拠していないためです](http://stackoverflow.com/q/33112559/2976878)。 – Hamish