"Initialization of immutable value never used"但实际使用

"Initialization of immutable value never used" but is actually used

我一直收到这个值从未使用过的错误。我知道此错误经常在 Swift 2.2 中弹出,这是因为未使用初始化的值。但是,我确实使用了这个值,并且这个错误在我使用的错误上弹出了 3 次,我不知道为什么我仍然得到它。

下面是代码。 "Difficulty" 是编译器说没有使用的变量,但是从我的代码可以看出,它实际上被使用了。有人知道为什么会这样吗?

class SettingsController: UIViewController {

// MARK: Properties

// Preferences for difficulty level of questions
let preferences = NSUserDefaults.standardUserDefaults()
let difficultyKey = "Difficulty"
let questionnumKey = "QuestionNum"
var difficulty: String = "EASY"


@IBOutlet weak var Easy: DLRadioButton!
@IBOutlet weak var Medium: DLRadioButton!
@IBOutlet weak var Hard: DLRadioButton!



override func viewDidLoad() {
    super.viewDidLoad()

    readUserDefaults()
    setDifficulty()

}

func readUserDefaults(){
    let difficulty = preferences.stringForKey(difficultyKey) // <--Error

}

func setDifficulty(){
    if difficulty == "HARD"{
        Hard.selected = true
    }
    else if difficulty == "MEDIUM"{
        Medium.selected = true
    }
    else{
        Easy.selected = true
    }

}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}

readUserDefaults()中应该是

difficulty = preferences.stringForKey(difficultyKey)

您需要删除 let:您之前已经创建了 difficulty 变量。

你还需要使用??,"nil coalescing operator":preferences.stringForKey(difficultyKey) ?? "EASY",例如,给一个值即使方法调用returns nil.

注意:根据@eric-d 和@leo-dabus 的评论做出的回答。