2017-10-03 17 views
-1

私は同じ問題に関連するいくつかのトピックをチェックしましたが、私自身のコード内でこの問題の解決策を見つけることはできません...メソッドはスーパークラスのメソッドをオーバーライドしません(Swift 4、Xcode 9)

Piano:Instrumentサブクラスで関数tune()をオーバーライドしようとすると、エラーが発生します。

スーパークラスの元の関数をコピーして、構文が厳密に同じであることを確認しています。

また、super.initメソッドが意図したとおりに動作するように見えるので(コンパイラエラーなし)、サブクラスがうまくいくようです。

私のエラーはどこですか?

コード:

class Music { 

    let notes: [String] 

    init(notes: [String]) { 
     self.notes = notes 
    } 

    func prepared() -> String { 
     return notes.joined(separator: " ") 
    } 

} 

class Instrument { 

    let model: String 

    init(model: String) { 
     self.model = model 

     func tune() -> String { 
      fatalError("Implement this method for \(model)") 
     } 

     func play(_ music: Music) -> String { 
      return music.prepared() 
     } 

     func perform(_ music: Music) { 
      print(tune()) 
      print(play(music)) 
     } 

    } 

} 

class Piano: Instrument { 

    let hasPedals: Bool 

    init(hasPedals: Bool, model: String) { 
     self.hasPedals = hasPedals 
     super.init(model: model) 

    } 

    override func tune() -> String { 
     fatalError("Implement this method for \(model)") 
    } 

} 

class Guitar: Instrument { 

    let hasAmplifyer: Bool 

    init(hasAmplifyer: Bool, model: String) { 
     self.hasAmplifyer = hasAmplifyer 
     super.init(model: model) 

    } 

} 

はどうもありがとうございました!

答えて

0

tuneplay、およびperformの機能がinitの機能の中に誤って定義されています。トップレベルに移動:

class Instrument { 

    let model: String 

    init(model: String) { 
     self.model = model 
    } 

    func tune() -> String { 
     fatalError("Implement this method for \(model)") 
    } 

    func play(_ music: Music) -> String { 
     return music.prepared() 
    } 

    func perform(_ music: Music) { 
     print(tune()) 
     print(play(music)) 
    } 

} 

スウィフトは、それがInstrumentでトップレベルにあることを期待ので、オーバーライドするtune機能を見ません。

+0

Omg、ありがとうございます!それは今あなたがそれを言っていることは明らかだ... – Pandemonium

関連する問題