Swift: 用常量字符串声明常量数组
Swift: Declaring constant array with constant strings
我正在实现一个 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]
}
然而,当我尝试将数组声明为 class 变量并添加静态字符串时,出现以下错误:
'name.Type' 没有名为 'titleOne'
的成员
我已阅读以下内容并理解为什么以上内容不可能:'Class.Type' does not have a member named 'variable' error just a lack of class variable support?
有没有一种方法可以优雅地使用常量字符串创建数组,而无需在数组中使用字符串文字,也无需在方法中进行操作?我在想也许是一个结构?或者这是矫枉过正?
谢谢。
感谢“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]
}()
我正在实现一个 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]
}
然而,当我尝试将数组声明为 class 变量并添加静态字符串时,出现以下错误:
'name.Type' 没有名为 'titleOne'
的成员我已阅读以下内容并理解为什么以上内容不可能:'Class.Type' does not have a member named 'variable' error just a lack of class variable support?
有没有一种方法可以优雅地使用常量字符串创建数组,而无需在数组中使用字符串文字,也无需在方法中进行操作?我在想也许是一个结构?或者这是矫枉过正?
谢谢。
感谢“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]
}()