Robert Plant Robert Plant - 7 months ago 9
Swift Question

Modifying a Class to Display Specific Output (Swift)

I am new to Swift and am having a bit of trouble with this bit in particular. Attached is some code I need to run as part of a project. Details are at the end.

class Screen:DataSource {
var items:[String]=[]
func run(){
let lv = TableView()
items = ["John","Paul","George","Ringo"]
let ds = self
lv.dataSource=ds
lv.drawList()
}
}

class TableView {
// This class displays a list given a DataSource
var dataSource:DataSource?
init (){
self.dataSource=nil
}

func drawList(){
for(var i=0;i<dataSource!.getSize();i++) {
print("\(dataSource!.getItem(at:i))")
print("--------------------------")
}
}
}

protocol DataSource {
func getSize()->Int
func getItem(at pos:Int)->String
}

let screen = Screen()
screen.run()


Without changing the "run" function/method, I need to have it print this:

John
--------------------------
Paul
--------------------------
George
--------------------------
Ringo
--------------------------


I'm not sure what to modify in my Screen class. This is what I have so far:

class Screen: DataSource {
var items: [String]=[]   
func run() {       
let lv = TableView()       
items = ["John","Paul","George","Ringo"]       
let ds = self       
lv.dataSource=ds       
lv.drawList()   
}
//NEED HELP HERE
}


Any tips would be appreciated.

Answer

Use an extension to make Screen conform to DataSource:

 class Screen {
    var items:[String]=[]
    func run(){
        let lv = TableView()
        items = ["John","Paul","George","Ringo"]
        let ds = self
        lv.dataSource=ds
        lv.drawList()
    }
}

extension Screen: DataSource {
    func getSize() -> Int { return items.count }
    func getItem(at index:Int) -> String { return items[index] }
}

You could also put the DataSource conformance and methods on the class itself, but doing it in an extension is a common style for organizing your class's members.

Comments