使用非整数增量创建数组

时间:2017-01-06 19:22:56

标签: arrays swift

我正在尝试在Swift中创建时间戳数组。

所以,假设我想要从0到4秒,我可以使用Array(0...4),这会[0, 1, 2, 3, 4]

但我怎样才能获得[0.0, 0.5 1.0, 2.0, 2.5, 3.0, 3.5, 4.0]

基本上我想要一个灵活的增量,例如0.50.05等。

2 个答案:

答案 0 :(得分:6)

您可以使用stride(from:through:by:)

#include <type_traits>

template <int L>
class MyInteger {};

template <int L, int M>
constexpr auto operator+(const MyInteger<L> &lhs, const MyInteger<M> &rhs) {
    return MyInteger<(L > M ? L : M)>{};
}

int main() {
    constexpr MyInteger<0> m1;
    constexpr MyInteger<1> m2;
    static_assert(std::is_same<decltype(m1 + m2), MyInteger<1>>::value, "!");
}

答案 1 :(得分:0)

非常数增量的替代方案(在Swift 3.1中更可行)

@Alexander's answer中涵盖的stride(from:through:by:)函数是 适用于目的解决方案,但对于此Q&amp; A的读者想要构建序列的情况( 非常数增量(在这种情况下线性序列构建stride(...)不足),我还将包括另一种选择。

对于这种情况,sequence(first:next:)是一种很好的选择方法;用于构造一个可以重复查询下一个元素的惰性序列。

,构建log10比例(Double数组)的前5个滴答

let log10Seq = sequence(first: 1.0, next: { 10*$0 })
let arr = Array(log10Seq.prefix(5)) // [1.0, 10.0, 100.0, 1000.0, 10000.0]

Swift 3.1计划于2017年春季发布,随之而来(在许多其他事情中)实现了以下公认的Swift演进提案:

prefix(while:)sequence(first:next)结合使用,提供了一个简洁的工具,可以生成包含简单next方法(例如模仿stride(...)的简单行为)的所有内容的序列。那些。此问题的stride(...)示例是此类用法的一个很好的最小(非常简单)示例:

/* this we can do already in Swift 3.0 */
let delta = 0.05
let seq = sequence(first: 0.0, next: { $0 + delta})

/* 'prefix(while:)' soon available in Swift 3.1 */
let arr = Array(seq.prefix(while: { $0 <= 4.0 }))
    // [0.0, 0.5, 1.0, 1.5, 2.0, 2.5, 3.0, 3.5, 4.0]

// ...
for elem in sequence(first: 0.0, next: { $0 + delta})
    .prefix(while: { $0 <= 4.0 }) {
        // ...
}

同样,在{Q}的简单情况下,不与stride(...)竞争,但只要stride(...)的有用但简单的应用不足,用于构建非线性序列。