0

I'm having a few issues in building a search bar for searching a list of work types for a project I am building. I am getting a lot of red exclamation points saying "tblSearchResults" is an unresolved identifier.

Here is a the project source code where the issue is occurring.

    func WorkTypeSearchable() {

    let pathToFile = NSBundle.mainBundle().pathForResource("work", ofType: "txt")

    if let path = pathToFile {

        let workString = String(contentsOfFile: path, encoding:
NSUTF8StringEncoding, error: nil)!

        let WorkTypeSearchable = workString.componentsSeparatedByString("\n")

        tblSearchResults.reloadData()
    }
}

Can you explain why I would be getting an error as an unresolved identifier, as well as well an error with my string for "workString = String(code)...

I am using all the appropriate classes as seen here:

class ViewController: UIViewController, UIPickerViewDataSource,
UIPickerViewDelegate, UITableViewDelegate, UITableViewDataSource,
UISearchResultsUpdating, UISearchBarDelegate {

Note that I am also using a picker later in the program.

Seth Kerr
  • 27
  • 8

1 Answers1

0

An unresolved identifier error indicates that Xcode cannot find where you defined tblSearchResults. Did you connect an IBOutlet and initialize the delegate? Implementing the delegate alone will not cause tblSearchResults to point to the UITableView you want.

To create an IBOutlet, open the Assistant Editor, then Control-Drag from the UITableView to just below your class declaration, and change the type to Outlet and the name to tblSearchResults. Then, you will probably also want to initialize the delegate and dataSource in the viewDidLoad(), like this:

class ViewController: UIViewController, UIPickerViewDataSource, UIPickerViewDelegate, UITableViewDelegate, UITableViewDataSource, UISearchResultsUpdating, UISearchBarDelegate {
    @IBOutlet weak var tblSearchResults: UITableView!
    override func viewDidLoad() {
        tblSearchResults.delegate = self
        tblSearchResults.dataSource = self
        //Insert other initialization code here
    }
}

String Init: Swift 1 vs. Swift 2

You mentioned that you are using Swift 2, which no longer uses the String initialization method you used in your code. There are two differences:

  1. You must use NSString instead of String
  2. You must use a try statement

Try this: (please note that it is unsafe, the app will crash if the file can't be read)

let text2 = try! NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding)
Community
  • 1
  • 1
BradzTech
  • 2,755
  • 1
  • 16
  • 21
  • This helped immensely. I suppose I should make sure the resources I use in the future are for the most current version of Swift. – Seth Kerr Mar 15 '16 at 20:15
  • Good idea. In addition to major features like error handling, several minor things were changed, which can get annoying if you're looking at Swift 1 code. Glad I could help! – BradzTech Mar 15 '16 at 20:22