Search code examples
iosswiftuilabelnsobject

Displaying NSObject init in label


I have a simple viewcontroller which displays two labels, one with a quote and one with its author. The quotes and authors are put in a NSObject (see code) and the shown quote/author is randomized. My problem is how to show the quote and author in the specific label.

 class Quotes: NSObject {
        var person : String
        var quote  : String

        init(person : String, quote : String) {
            self.person = person
            self.quote = quote
        }
    }

    let quotes = [

        Quotes(person: "Person1", quote: "Quote1"),
        Quotes(person: "Person2", quote: "Quote2"),
        Quotes(person: "Person3", quote: "Quote3" ),  ]


    override func viewDidLoad() {
    super.viewDidLoad()

        let range: UInt32 = UInt32(quotes.count)
    let randomNumber = Int(arc4random_uniform(range))
    let QuoteString = quotes.person.objectAtIndex(randomNumber) //ERROR here, how do I specify the choosen author from the randomization?  
    let AuthorString = quotes.quote.objectAtIndex(randomNumber)//ERROR here, how do I specify the choosen quote from the randomization?  


    self.quoteLabel.text = QuoteString as? String
    self.personLabel.text = NameString as? String

}

I imagine it's a really easy solution, would really appreciate help (I'm new to programming)


Solution

  • You have your array & property access slightly mixed up. First, access the Quote object from the array and then access the object's properties

    let randomNumber = Int(arc4random_uniform(self.quotes.count))
    let quote = self.quotes[randomNumber]
    let quoteString = quote.quote
    let authorString = quote.author
    
    self.quoteLabel.text = quoteString
    self.personLabel.text = authorString