【问题标题】:number of array elements at compile time编译时数组元素的数量
【发布时间】:2015-02-08 13:34:09
【问题描述】:

我想知道编译时 Array 元素的数量:

let sections = ["A","B","C"]

// I want fill later this Array with Arrays of type Product
var productsInSection = [[Product]](count:number of Array elements from sections array, repeatedValue:[])

我的问题是我可以使用什么:“sections 数组中的数组元素数” 所以我不必看,如果我随时改变

let sections = ["A","B","C","D"]

【问题讨论】:

  • 您使用的是特定的编程语言吗?
  • 如果你真的需要在编译时计数,从资源文件中读取数组似乎是最直接的方法。如果这不是一个选项,我会尝试混合一些 Objective C 并在预编译头文件中添加一些宏。唯一的问题是我不明白为什么在你的情况下需要它。

标签: arrays swift compile-time


【解决方案1】:

我不明白你为什么需要“编译时间”。

但我认为count property 足以满足您的需求:

let sections = ["A","B","C"]
var productsInSection = [[Product]](count:sections.count, repeatedValue:[])

添加回答评论

例如:

private let _indexSectionTitles = ["A","B","C","D","E","F","G","H","I","J","K","L","M", "N","O","P","Q","R","S","T","U","V","W","X","Y","Z", "Ä","Ö","Ü", "#" ]

class MyClass{
    let indexSectionTitles = _indexSectionTitles
    var productsInSection = [[GlobalProduct]](count: _indexSectionTitles.count, repeatedValue: [])
}

【讨论】:

  • class MyClass{ 让 indexSectionTitles = [ "A","B","C","D","E","F","G","H","I" ,"J","K","L","M","N","O","P","Q","R","S","T","U"," V","W","X","Y","Z", "Ä","Ö","Ü", "#" ] var productsInSection = [[GlobalProduct]](count: indexSectionTitles.count,重复值:[])我得到一个编译错误:“MyClass.Type”没有名为“indexSectionTitles”的成员
  • 谢谢!!诀窍是把它放在类声明之外。现在它对我有用!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 2013-09-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-08-04
相关资源
最近更新 更多