使用带有字符串swift的integerForKey

时间:2015-02-22 02:36:34

标签: ios swift

我很担心在swift中使用整数键。有人可以解释这是如何工作的,它会带来什么价值?我希望它能够返回与字典或数组中的键相关联的整数,但不知道它将如何返回字符串的整数?

import Foundation

// adopted by delegate so it can be notified when settings change
protocol ModelDelegate {
    func settingsChanged()
}

class Model {
    private let regionsKey = "FlagQuizKeyRegions"
    private let guessesKey = "FlagQuizKeyGuesses"

    // reference to QuizViewController to notify it when settings change
    private var delegate: ModelDelegate! = nil

    var numberOfGuesses = 4 // number of guesses to display

    private var enabledRegions = [
        "Africa" : false,
        "Asia" : false,
        "Europe" : false,
        "North_America" : true,
        "Oceania" : false,
        "South_America" : false
    ]

    // variables to maintain quiz data
    let numberOfQuestions = 10
    private var allCountries: [String] = [] // list of all flag names
    private var countriesInEnabledRegions: [String] = []

    // initialize the settings from the app's NSUserDefaults
    init(delegate: ModelDelegate, numberOfQuestions: Int) {
        self.delegate = delegate

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

        // get number of guesses
        let tempGuesses = userDefaults.integerForKey(guessesKey)
        if tempGuesses != 0 {
            numberOfGuesses = tempGuesses
        }

1 个答案:

答案 0 :(得分:1)

它将为一个String返回一个Integer。所以,让我们说:

let myKey = "Countries"
let myCountries = ["USA","Brazil","Japan"]
NSUserDefaults.standardUserDefaults().setInteger(myCountries.count, forKey: myKey)
let numberOfCountries =  NSUserDefaults.standardUserDefaults().integerForKey(myKey)   // 3