Michael
Michael

Reputation: 47

How to Print an Array as Rows in a Label (Swift 3)

By rows I mean each row is a different index of the array (in order).

Here's my class that would hold a list of songs (array is empty as of now because the user needs to enter the songs, which is done in another ViewController):

class Songs {
private var _songs : [String]
var songs : [String]
    {
    get
    {
        return _songs
    }
    set (newSongs)
    {
        _songs = newSongs
    }
}

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

func songList() -> [String] {
    let songs = _songs
    return songs
}
}
var songList = Songs (songs: [String]())

The third ViewController in which I want the label to display the array:

class ThirdViewController: UIViewController {
// Properties
@IBOutlet weak var songList_lbl: UILabel!

override func viewDidLoad() {
    super.viewDidLoad()

    var multiLineString = songList.songList()
    multiLineString.joined(separator: "\n") // warning telling me separator is unused

    songList_lbl.text = multiLineString // error telling me cannot assign value of type '[String]' to type 'String?'
    songList_lbl.numberOfLines = 0 // code I found but haven't tested out yet
    songList_lbl.lineBreakMode = NSLineBreakMode.byWordWrapping
    songList_lbl.sizeToFit()

    // Do any additional setup after loading the view.
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

I also tried dumping the array, but I still get the value type error.

Upvotes: 0

Views: 806

Answers (1)

Josh Homann
Josh Homann

Reputation: 16327

Joined has a "ed" on it, and in swift that indicates is a copy, not a mutating method. You have to assign to the copy that it returns like:

songList_lbl.text = multiLineString.joined(separator: "\n")

Upvotes: 1

Related Questions