Hacker Newsnew | past | comments | ask | show | jobs | submitlogin

I have used inheritance twice in the past two years. Here is the most recent example. The code is from an iOS application written in Swift. The task was to write a quiz application. I used a combination of a protocol and a base class to avoid duplicating the code to advance to the next question. All view controllers implement the Scorable protocol and the view controllers for individual questions all inherit from ScorableViewController.

// Scorable.swift

import Foundation

  protocol Scorable {
    var totalScore : Int {get set}
  }

// ScorableViewController.swift

import UIKit

class ScorableViewController: UIViewController, Scorable {

    //overrides here...
    
    //This class exists to share the following code.
    var totalScore : Int = 0
    var currentChoice : Selection? = nil
    
    final var choseOption : Bool {
        get {
            return currentChoice != nil
        }
    }
    
    final override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
        precondition(choseOption, "must choose option before proceeding")
        precondition(segue.identifier != nil, "identifier is nil")
        precondition(!segue.identifier!.isEmpty, "identifier is empty")
        var dest = segue.destination as! Scorable
        dest.totalScore = Selection.add(score: totalScore, selection: currentChoice!)
    }
}


Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: