Swift:用常量字符串声明常量数组

时间:2015-03-18 14:59:39

标签: ios arrays uitableview swift constants

我正在实现一个UITableview,我想拥有一个包含每个部分标题的数组。

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

let headerTitles = [titleOne, titleTwo, titleThree]

这样我就可以通过以下方法访问数组:

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

    return headerTitles[section]
}

但是,当我尝试将数组声明为类变量并添加静态字符串时,我收到以下错误:

' name.Type'没有名为' titleOne'

的成员

我已阅读以下内容并了解上述原因无法解决的原因:'Class.Type' does not have a member named 'variable' error just a lack of class variable support?

有没有办法优雅地使用常量字符串创建数组而不使用数组中的字符串文字,也没有在方法中执行它?我想也许是一个结构?或者这有点过头了吗?

感谢。

1 个答案:

答案 0 :(得分:5)

感谢上面的评论“Martin R”。

以下是工作代码:

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]
}()