jeudi 19 février 2015

If statements in swift

I am new to swift and trying to understand this code that I am reading out of a book. Can somebody explain the if statement that sets the private searches Dictionary? Also what does the statement pairs as [String : String] mean? I am confused about the term as.Also I don't understand how the if statement is executed if you are declaring a constant and not comparing it? Shouldn't the if statement check for something then execute the following code if that is true?



import Foundation

// delegate protocol enables Model to notify controller when data changes
protocol ModelDelegate {
func modelDataChanged()
}

// this will manage the saved searches
class Model {
// keys used for storing the app's data in app's NSUserDefaults
private let pairsKey = "TwitterSearchesKVPairs"
private let tagsKey = "TwitterSearchesKeyOrder"

private var searches: Dictionary <String, String> = [:] // stores tag-query pairs
private var tags: Array<String> = [] // stores tags in user-specified order

private let delegate: ModelDelegate // delegate is MasterViewController

// initializes the Model object aka constructor
init(delegate: ModelDelegate) {
self.delegate = delegate

// get the NSUserDefaults object for the app
let userDefaults = NSUserDefaults.standardUserDefaults()

// get Dictionary of the app's tag-query pairs
if let pairs = userDefaults.dictionaryForKey(pairsKey) {
self.searches = pairs as [String : String]
}

// get Array with the app's tag order
if let tags = userDefaults.arrayForKey(tagsKey) {
self.tags = tags as [String]
}

Aucun commentaire:

Enregistrer un commentaire