2016-05-25 11 views
0

カスタムクラスを返すメソッドをオーバーライドする方法はありますか?このメソッドをオーバーライドするときメソッドをカスタムクラスの戻り値の型でオーバーライドできません

class CustomClass { 
    var name = "myName" 
} 

class Parent: UIViewController { 

    override func viewDidLoad() { 
    methodWithNoReturn() 
    print(methodWithStringAsReturn()) 
    methodWithCustomClassAsReturn() 
    } 

} 

extension Parent { 

    func methodWithNoReturn() { } 
    func methodWithStringAsReturn() -> String { return "Parent methodWithReturn" } 
    func methodWithCustomClassAsReturn() -> CustomClass { 
    return CustomClass() 
    } 

} 


class Child: Parent { 

    override func methodWithNoReturn() { 
    print("Can override") 
    } 

    override func methodWithStringAsReturn() -> String { 
    print("Cannot override") 
    return "Child methodWithReturn" 
    } 

    override func methodWithCustomClassAsReturn() -> CustomClass { 
    return CustomClass() 
    } 

} 

エラーは、次のとおりです:

私は戻り値の型としてカスタムクラスを任意のメソッドをオーバーライドしようとすると、Xcodeはエラー以下

は私のコードです私をスローします

FUNC methodWithCustomClassAsReturn() - > CustomClass

エラーメッセージで:

拡張子からの

宣言はまだ

+0

同様の問題:http://stackoverflow.com/questions/27109006/can-you-override-between-extensions-in-swift-or-not-compiler-seems-confused。 –

答えて

2

コンパイラはまだそれをサポートしていない以外の理由を上書きすることはできません。スーパークラスの拡張で定義されたメソッドをオーバーライドするには、あなたはそれがにObjC互換宣言する必要があります。

extension Parent { 
    func methodWithNoReturn() { } 
    func methodWithStringAsReturn() -> String { return "Parent methodWithReturn" } 

    @objc func methodWithCustomClassAsReturn() -> CustomClass { 
     return CustomClass() 
    } 
} 

// This means you must also expose CustomClass to ObjC by making it inherit from NSObject 
class CustomClass: NSObject { ... } 

代替を、すべてにObjCのsnafusを介さずにすることはない拡張子内部Parentクラスでこれらのメソッドを(定義することです):

class Parent: UIViewController { 

    override func viewDidLoad() { 
    methodWithNoReturn() 
    print(methodWithStringAsReturn()) 
    methodWithCustomClassAsReturn() 
    } 

    func methodWithNoReturn() { } 
    func methodWithStringAsReturn() -> String { return "Parent methodWithReturn" } 
    func methodWithCustomClassAsReturn() -> CustomClass { 
    return CustomClass() 
    } 

} 
+0

素敵でストレートな答えです。ありがとう! – WKL

関連する問題