1

I've declared the following:

class Song: CustomStringConvertible {
    let title: String
    let artist: String

    init(title: String, artist: String) {
        self.title = title
        self.artist = artist
    }

    var description: String {
        return "\(title) \(artist)"
    }
}

var songs = [
    Song(title: "Song Title 3", artist: "Song Author 3"),
    Song(title: "Song Title 2", artist: "Song Author 2"),
    Song(title: "Song Title 1", artist: "Song Author 1")
]

I want to enter this information into a UITableView, specifically at the tableView:cellForRowAtIndexPath:.

Such as this:

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

    cell.titleLabel = //the song title from the CustomStringConvertible[indexPath.row]
    cell.artistLabel = //the author title from the CustomStringConvertible[indexPath.row]
}

How would I do this? I can't figure it out.

Thanks a lot!

Anh Pham
  • 2,108
  • 9
  • 18
  • 29
Jacob Cavin
  • 2,169
  • 3
  • 19
  • 47

2 Answers2

0

I think you may be conflating CustomStringConvertible with some other design patterns. First, an answer:

// You have some container class with your tableView methods
class YourTableViewControllerClass: UIViewController {

    // You should probably maintain your songs array in here, making it global is a little risky

    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell
    {
        var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell

        // Get the song at the row
        let cellSong = songs[indexPath.row]

        // Use the song
        cell.titleLabel.text = cellSong.title
        cell.artistLabel.text = cellSong.artist
    }
}

Because the cell's title/artist are already public strings, you can just use them as you need. CustomStringConvertible will allow you to use the actual object itself as a String. So, in your case, you could have a song and call song.description and it would print out "title artist". But if you want to use the song's title and artist, you should just call song.title and song.artist. Here's the documentation on that protocol.

Also, as I wrote above, try moving your songs array into your ViewController. And maybe consider using structs instead of classs for your Song type.

tbogosia
  • 315
  • 1
  • 10
0

First, your Controller must implement UITableViewDataSource. Then,

func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
    var cell : LibrarySongTableViewCell! = tableView.dequeueReusableCell(withIdentifier: "Library Cell") as! LibrarySongTableViewCell
    cell.titleLabel?.text = songs[indexPath.row].title
    cell.artistLabel?.text =songs[indexPath.row].artiste
}