SearchResult class

Hi,

When you define SearchResult class, why you initialize some optional variables to empty strings? The code is below:

var artistName: String? = “”
var trackName: String? = “”
var kind: String? = “”
var trackPrice: Double? = 0.0
var currency = “”
var imageSmall = “”
var imageLarge = “”
var trackViewUrl: String?
var collectionName: String?
var collectionViewUrl: String?
var collectionPrice: Double?
var itemPrice: Double?
var itemGenre: String?
var bookGenre: [String]?

var name: String {
    return trackName ?? ""
}

I don’t see the point to the initialization. When parse the json data, if artistName is not a key in the dictionary, then the artistName will be given nil; if artistName is a key, then the artistName variable will be given a string value. Is that necessary to initialize the artistName at declaration?

@jiang Thanks very much for your question!

You make a very strong point here, and I do agree that it is unnecessary to add default values. Having said that, one reason why a default value is provided is to ensure that a value for the property is always given, and thus, the key always appears in the output. I personally have worked with JSON and often times, if the key value is nil, the property will not appear in your display.

I hope this helps!

All the best!

This topic was automatically closed after 166 days. New replies are no longer allowed.