所以我试图填充一个大小为 365 的数组,数组中的每个值都应该显示一天前的一天,代码的第一行 stepy.step.apppend(steps) 填充数组healthkit 提供的步骤数据,但是我从没有步骤的日子里什么也得不到,我需要用 0 填充未使用的日子,以便稍后为步骤设置正确的日期。
编辑:也就是说,我以特定日期的形式从 healthkit 获取步骤,但是从没有步骤的日子里我什么也得不到,我需要用 0 值填充这些日子。我想通过首先添加步骤来做到这一点,并且对于每天为 0 或 null 我添加数字 0
stepy.step.append(Int(steps))
let numbers = 1...365
let numberCount = numbers.count
var products = [Int]()
products.reserveCapacity(numberCount)
for number in numbers {
if stepy.step.contains(numbers != 0)
{
let product = (number * 0)
print(product)
stepy.step.append(product)
}
}
最佳答案
也许就是这样
if stepy.step.contains(numbers != 0)
应该是
if stepy.step.contains(number != 0)
(比较次数次迭代,而不是范围。)
但是话又说回来,number != 0
返回一个 Bool
,包含 true/false 没有意义。
仅与问题松散相关的方法
但为了好玩,这里有一种不同的方法来初始化具有一定容量的数组并在适当的地方插入值。
请注意,我添加了很多关于 OP 希望通过 contains
检查和所有内容实现的个人解释,因为 OP 发布的内容没有计算任何内容:
stepy.step.append(Int(steps))
// Indicated `stepy.step` is of type `[Int]`
// If you have to start with an input range, you can use:
// (1...365).map { _ in 0 }
let stepsOfLastYear: [Int] = Array(repeating: 0, count: 365)
.enumerated() // A different way to obtain an index like in a for loop
.map { index, value in
// The only containment check that makes sense: was the
// source array large enough? -- If not, pass back 0.
guard stepy.step.indices.contains(index) else { return value }
return stepy.step[index] }
关于ios - 填充 365 的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46788277/