2

I am implementing a UITableview and I want to have an array that holds the titles for each section.

let titleOne = "Hello World"
let titleTwo = "What's next"
let titleThree = "Extras"

let headerTitles = [titleOne, titleTwo, titleThree]

This is so that I can access the array in the following method:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

    return headerTitles[section]
}

However when I try and declare the array as a class variable and add the static strings I get the following error:

'name.Type' does not have a member named 'titleOne'

I have read the following and understand why the above is not possible: 'Class.Type' does not have a member named 'variable' error just a lack of class variable support?

Is there a way to elegantly create the array with the constant strings without using string literals in the array and also without doing it in a method? I am thinking maybe a Struct? Or is this overkill?

Thanks.

Community
  • 1
  • 1
pls
  • 1,522
  • 2
  • 21
  • 41
  • This seems like it should work just fine. Sometimes Option clicking on variable names will help me track down issues like this. For example: Holding down the Option Key and clicking on the `headerTitles` variable in the function should show that the `headerTitles` variable is an array of Strings. i.e. `[String]` There should be now problems subscripting into an array of strings to get the value you want back out. – JMFR Mar 18 '15 at 15:05
  • Hi JMFR, thanks for the response. I have edited the question as I realised I had written it badly. The problem is when I try and declare the array and add the static strings. – pls Mar 18 '15 at 15:14
  • 2
    If I see it correctly, you have defined properties where the initialization of one property depends on another property of the same class. Compare http://stackoverflow.com/questions/25854300/how-to-initialize-properties-that-depend-on-each-other, http://stackoverflow.com/questions/26423906/swift-class-myclass-does-not-have-a-member-named-my-var. – Martin R Mar 18 '15 at 15:16
  • Hi Martin, thanks for the links. The first one has led me to the solution. I will post an answer with my working code. – pls Mar 18 '15 at 15:30

1 Answers1

5

Thanks to 'Martin R' for his comment above.

Here is the working code:

let titleOne = "Hello World"
let titleTwo = "What's next"
let titleThree = "Extras"

lazy var sectionHeaders: [String] = {
    [unowned self] in
    return [self.titleOne, self.titleTwo, self.titleThree]
}()
Community
  • 1
  • 1
pls
  • 1,522
  • 2
  • 21
  • 41