Search code examples
arraysclassswifttableviewsuperclass

How to build object hierarchy such that all nouns are words but not all words are nouns


I have a couple of classes that represent parts of speech (nouns, verbs, adjectives, pronouns...) written in swift. I want to display instances of these classes in the same table view. All of these classes are types of words so technically there should be a class called word that is the superclass of noun.swift, verb.swift, adjective.swift and the others. Not all of those word types have the same member variables. How should I go about reconciling these objects as different types of words.

Alternatively I have been considering making the array of the type Any and adding objects of different types to it. That array will hold all of the values in the table view. The issue there is passing the object of undeclared type to the detailViewController.

If anyone has any advice on how to proceed it would be much appreciated.


Solution

  • If nouns, verbs, etc are in fact types of words then that must be captured in the type hierarchy. As soon as you wrote class Noun and then class Verb you needed to stop and define the superclass.

    class Word {}
    class Noun : Word { /* ... */ }
    class Verb : Word { /* ... */ }
    

    The above is the minimum; the starting point. From here, you add state or behavior to Word as you recognize that Noun and Verb share something.

    Now you can have arrays of words. Of course, if there is no state nor behavior associated with a Word then all users of that array will forever be down casting to one of the subtypes:

    override func tableView (tableView: UITableView, 
     cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
    
      let cell = ...
      let word = words[indexPath.row]
    
      if let noun = word as? Noun { cell.text = /* noun stuff */ }
      else if let verb = word as? Verb { cell.text = /* verb stuff */ }
    
      return cell
    }
    

    But I suspect, once you've defined Word, you'll find stuff to put in it which will make the above word as? Noun code less onerous.

    Note regarding the type hierarchy: I'd say, strictly, nouns and verbs are actually parts of speech and that a word can be associated with multiple parts of speech. Modeled as such:

    class PartOfSpeech {}
    class Noun : PartOfSpeech {}
    class Verb : PartOfSpeech {}
    
    class Word { var partsOfSpeech : Set<PartOfSpeech> }