【问题标题】:Swift: Declaring constant array with constant stringsSwift:用常量字符串声明常量数组
【发布时间】:2015-05-21 10:28:51
【问题描述】:

我正在实现一个 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?

有没有一种方法可以优雅地创建具有常量字符串的数组,而无需在数组中使用字符串文字,也无需在方法中进行操作?我在想也许是一个结构?或者这是矫枉过正?

谢谢。

【问题讨论】:

  • 这看起来应该可以正常工作。有时,单击变量名称的选项将帮助我追踪此类问题。例如:按住 Option 键并单击函数中的headerTitles 变量应该会显示headerTitles 变量是一个字符串数组。即[String] 现在应该有问题下标到字符串数组以获取您想要的值。
  • 您好 JMFR,感谢您的回复。我已经编辑了这个问题,因为我意识到我写得不好。问题是当我尝试声明数组并添加静态字符串时。
  • 如果我没看错,您已经定义了一个属性的初始化依赖于同一类的另一个属性的属性。比较stackoverflow.com/questions/25854300/…stackoverflow.com/questions/26423906/…
  • 嗨马丁,感谢您的链接。第一个使我找到了解决方案。我会用我的工作代码发布答案。

标签: ios arrays uitableview swift constants


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-12
    • 2011-04-01
    • 2010-12-21
    • 2010-11-28
    • 2012-10-19
    • 1970-01-01
    相关资源
    最近更新 更多