Search code examples
iosiphoneswiftfor-in-loop

How to print Custom Class in For In loop in Swift?


I have a custom class, as follows in Swift

import UIKit

class NewsDealDao: NSObject
{
    var dealID: NSString = ""
    var discountPercent: NSString = ""
    var dealName: NSString = ""
    var dealProvider: NSString = ""
    var descriptionDeal: NSString = ""
    var expiryDate: NSString = ""
    var partnerLevelName: NSString = ""
    var logoPath: NSString = ""
    var categoryName: NSString = ""
    var websiteURL: NSString = ""
    var favourite: NSString = ""
    var distance: NSString = ""

}

Now I made its objects, fetched from XML and put inside an Array, i.e news_array.

I want to see values in side Array.

In Objective-C, I could code like

for (NewsDealDao *news in news_array){
      NSLog(@"News is %@", news.dealName);
}

While in Swift, I tried, 

for news in news_array {

            println ("\(news)")
        }

Also I tried following code, but it crashes,

 for var index = 0; index < news_array.count; index++ {

            println("Hello \(index)")


            var news: NewsDealDao = news_array.objectAtIndex(index)

            println("New is \(news.dealName)")


        }




var array_newsDeal = NSMutableArray() //This is how array is made,
//This is protocol
protocol NewsDeal_ParserDelegate {

    func parsingWasFinished(newsDeal_array: NSMutableArray)
}

 //This is adding objects to array, when Tag is called.

 if elementName == "DealDetails" {
            array_newsDeal.addObject(NewsDealDao)
        }

 //Returning array via Protocol to previous class. Where I wana see result.

 func parserDidEndDocument(parser: NSXMLParser) {

        delegate?.parsingWasFinished(array_newsDeal)

    }

Any solution, How can I see variables inside my class objects, which are stored in Array.

Thanks.


Solution

  • I guess you use NSArray,so try this code:

    var news: NewsDealDao = news_array.objectAtIndex(index) as NewsDealDao
    

    In swift,objectAtIndex return AnyObject,you have to convert it to the class type you want

    Update: I think this line is wrong

    array_newsDeal.addObject(NewsDealDao)
    

    You should add a instance of NewsDealDao,not class