2015-12-30 9 views
6

は私のコードです:ジェネリック型のイニシャライザは迅速に継承されませんか?ここ

public class A<T : Any> { 
    public init(n : Int) { 
     print("A") 
    } 
} 
public class B : A<Int> { 
} 
public class C : B { 
} 
let x = C(n: 123) 

これは、コンパイルを失敗し、このようなエラーを叫ぶ:

repl.swift:9:9: error: 'C' cannot be constructed because it has no accessible initializers 

次のコードをコンパイルすることができます。

public class A { 
    public init(n : Int) { 
     print("A") 
    } 
} 
public class B : A { 
} 
public class C : B { 
} 
let x = C(n: 123) 

は、要件タイプを継承するジェネリック型の初期化子を指定していないでしょうか?

=======

“Superclass initializers are inherited in certain circumstances, but only when it is safe and appropriate to do so. For more information, see Automatic Initializer Inheritance below.”
---Apple Inc. “The Swift Programming Language (Swift 2)” iBooks.

以下========追加そしてこの

“However, superclass initializers are automatically inherited if certain conditions are met.”

“Assuming that you provide default values for any new properties you introduce in a subclass, the following two rules apply:” Rule 1 “If your subclass doesn’t define any designated initializers, it automatically inherits all of its superclass designated initializers.” Rule 2 “If your subclass provides an implementation of all of its superclass designated initializers—either by inheriting them as per rule 1, or by providing a custom implementation as part of its definition—then it automatically inherits all of the superclass convenience initializers.”

最初のコードを検討して、サブクラスBのdoesn指定された初期化子を定義していない場合は、スーパークラス指定のイニシャライザをすべて自動的に継承する必要があります。A<Int>からのものです。

+1

こちらもご覧ください:http://stackoverflow.com/questions/31040044/swift-generic-superclass-init-not-accesible-when-constructing-its-subclass –

+0

誰かが迅速なjiraでチケットを申請しています。https://bugs.swift.org/projects/SR/issues/SR-416 –

+0

@AnthonyKongはい、それは私です。 – AntiMoron

答えて

1

私はオーバーライドコードとsuper.initを使用しようとすると、エラーではありません。私はジェネリック型の関数を初期化する必要はないと思います。

public override init(n:Int) { super.init(n: n) }

0

あなたの失敗のコードは今(スウィフト3以降)コンパイルし、クラスBと、このようなクラスC. ルックでオーバーライドinit関数を入れてみてください。 Swift 3 Language changesにこの変更については言及していないので、私はこれがバグだと仮定することしかできません。

関連する問題