jonthornham
jonthornham

Reputation: 3335

Dictionary Values in Swift

I am trying to access values I've set in a Swift dictionary. The dictionary has a String for the keys and values. My intent is to use the dictionary to set a string variable as I work through a series of URLs. In Objective-C I understand how this works. I have a string property called currentFeed that I pass the value of the dictionary to.

self.currentFeed = [NSString stringWithString: [self.URLDictionary objectForKey: @"FLO Cycling"]];

In Swift I am having a difficult time with this. I tried the following code and receive an error message.

self.currentFeed = self.URLDictionary["FLO Cycling"]

Error Message: "Cannot subscript a value of type '[String:String]' with an index of type 'String'.

For reference the dictionary was created in Swift in the following way. The constants were created with lets.

let kFLOCyclingURL = "http://flocycling.blogspot.com/feeds/posts/default?alt=rss"
let kTriathleteURL = "http://triathlon.competitor.com/feed"
let kVeloNewsURL = "http://velonews.competitor.com/feed"
let kCyclingNewsURL = "http://feeds.feedburner.com/cyclingnews/news?format=xml"
let kRoadBikeActionURL = "http://www.roadbikeaction.com/news/rss.aspx"
let kIronmanURL = "http://feeds.ironman.com/ironman/topstories"

The items were added to the dictionary with keys.

let URLTempDictionary = ["FLO Cycling" : kFLOCyclingURL, "Triathlete" : kTriathleteURL, "Velo News" : kVeloNewsURL, "Cycling News" : kCyclingNewsURL, "Road Bike Action" : kRoadBikeActionURL, "Ironman" : kIronmanURL]

Thanks for any help.

Take care,

Jon

Upvotes: 0

Views: 447

Answers (1)

Daniel Rushton
Daniel Rushton

Reputation: 578

This compiles fine for me. The only thing I noticed was that your dictionary is named URLTempDictionary and you're accessing URLDictionary. :)

Option a (safest, most robust)

if let dict = self.URLDictionary
{
    self.currentFeed = dict["FLO Cycling"]
}

Option b (use with caution, possible runtime error)

self.currentFeed = dict!["FLO Cycling"]

Upvotes: 1

Related Questions