数组初始化之谜,以重复值作为序列,Swift

thi*_*ift 2 arrays initialization sequence swift

尝试传递生成的序列(可能是更复杂的 struct 或 func 值),例如在数组初始化期间生成一些键字符串。

这是一个数组初始化字符串:

let MyArray: Array<Int> = Array<Int>(count: 100, repeatedValue:(for i in 0...99))
// it does not work, I am doing it wrong :(
// instead of (for i in 0...99) could be anything, a key sequence generator
Run Code Online (Sandbox Code Playgroud)

以下是文档中的内容:

/// Construct a Array of `count` elements, each initialized to
/// `repeatedValue`.
init(count: Int, repeatedValue: T)
Run Code Online (Sandbox Code Playgroud)

用生成或排序的值替换“T”的正确方法是什么。或者我不应该为此烦恼并让数组成为一个变量,然后再填充它?

谢谢。

Mar*_*n R 5

Array 有一个将序列作为参数的构造函数:

init<S : SequenceType where T == T>(_ s: S)
Run Code Online (Sandbox Code Playgroud)

示例: 范围是一个序列:

let a1 = Array(0 ..< 10)
println(a1)
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Run Code Online (Sandbox Code Playgroud)

映射接受一个序列并返回一个数组:

let a2 = map( 0 ..< 10) { i in i*i }
println(a2)
// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]
Run Code Online (Sandbox Code Playgroud)

自定义序列类型的示例(从https://codereview.stackexchange.com/a/60893/35991复制):

struct FibonacciSequence : SequenceType {
    let upperBound : Int

    func generate() -> GeneratorOf<Int> {
        var current = 1
        var next = 1
        return GeneratorOf<Int>() {
            if current > self.upperBound {
                return nil
            }
            let result = current
            current = next
            next += result
            return result
        };
    }
}

let fibseq = FibonacciSequence(upperBound: 100)
let a3 = Array(fibseq)
println(a3)
// [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Run Code Online (Sandbox Code Playgroud)

Swift 2 更新:

let a1 = Array(0 ..< 10)
print(a1)
// [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

let a2 = (0 ..< 10).map { i in i*i }
print(a2)
// [0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

struct FibonacciSequence : SequenceType {
    let upperBound : Int

    func generate() -> AnyGenerator<Int> {
        var current = 1
        var next = 1
        return anyGenerator {
            if current > self.upperBound {
                return nil
            }
            let result = current
            current = next
            next += result
            return result
        };
    }
}

let fibseq = FibonacciSequence(upperBound: 100)
let a3 = Array(fibseq)
print(a3)
// [1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89]
Run Code Online (Sandbox Code Playgroud)