如果语句迅速

时间:2015-02-20 02:36:25

标签: xcode swift if-statement

我是swift的新手并试图理解我正在读书的这段代码。有人可以解释设置私有搜索字典的if语句吗?语句对[String:String]的含义是什么意思?我对术语as感到困惑。如果你声明一个常数而不是比较它我也不明白如何执行if语句?不应该if语句检查某些内容然后执行以下代码,如果这是真的吗?

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]
        }

1 个答案:

答案 0 :(得分:2)

“if let”用于条件展开并用于安全地展开可选值。 “as”用于铸造但在这种情况下你需要用作? (条件铸造)。如果需要,您可以只用一个句子组合:

// 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]
}

也可以写成:

if let searches = NSUserDefaults.standardUserDefaults().dictionaryForKey(pairsKey) as? [String : String] {
    println(searches.description)
}

if let tags = NSUserDefaults.standardUserDefaults().arrayForKey(tagsKey) as? [String] {
    println(tags.description)
}


// [String : String]  means a Dictionary where its keys and values are String types

NSUserDefaults.standardUserDefaults().setObject(["book":"brown","car":"black"], forKey: "searches")

if let searches = NSUserDefaults.standardUserDefaults().dictionaryForKey("searches") as? [String : String] {
    println(searches["book"]!)  // "brown"
    println(searches["car"]!)   // "black"
}