Harold
Harold

Reputation: 45

let constant not seen in other function in class

The constant "jumbleDictionary" seems to not be recognized in the "solve:" method, after I declared it in viewDidLoad.

Why is this? I tried declaring it in top code, but I wanted to put Date() calls to measure the time it takes to load the NSDictionary, and that ran into "expecting a declaration" errors.

But putting it in a method seems to hide the symbol from other methods. I don't remember this being a problem in Objective-C - as I remember, all properties of a class could be used in all methods.

import Cocoa

class JumbleController: NSViewController {

@IBOutlet weak var scrambledWordField, solutionWordsField, elapsedTime: NSTextField!

override func viewDidLoad() {
    super.viewDidLoad()
    let jumbleDictionary: NSDictionary? = NSDictionary.init(contentsOfFile: Bundle.main.path(forResource: "BigDictionary", ofType: "plist")!)
}


@IBAction func solve(sender: NSTextField)
{
    let timeStart = Date.init()
    var userWordString = scrambledWordField.stringValue.lowercased()
    if Range(4...15).contains(userWordString.characters.count) {
        userWordString = String(Array(userWordString.characters).sorted())
        if let solutionWordArray = (jumbleDictionary?[userWordString] as? [String]?)!
        {
            let timeEnd = Date.init()
            solutionWordsField.stringValue = solutionWordArray.joined(separator: "\n").uppercased()
            elapsedTime.doubleValue = timeEnd.timeIntervalSince(timeStart)
        }
        else {
            solutionWordsField.stringValue = "No Solution Found."
        }
    }
    else {
        solutionWordsField.stringValue = "Must be 4 to 15 letters."
    }
}

}

List item

Upvotes: 0

Views: 53

Answers (1)

David Park
David Park

Reputation: 325

This is a matter of scope. When a variable is declared within a method. It is only visible to that method. Since jumbleDictionary is defined inside the viewDidLoad() method, it is only available there.

Try this:

var jumbleDictionary: NSDictionary?

override func viewDidLoad() {
    super.viewDidLoad()

    jumbleDictionary = //whatever you want

}

Upvotes: 2

Related Questions