数组初始化用repeatValue作为序列谜语,Swift

时间:2014-11-18 13:02:44

标签: arrays swift initialization sequence

尝试传递生成的序列(可能是更复杂的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

这里有什么文件说明:

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

什么是替换&#34; T&#34;生成或排序的值。或者我应该不打扰这个并将数组变成一个变量,稍后再填充它?

感谢。

2 个答案:

答案 0 :(得分:4)

Array有一个构造函数,它接受一个序列作为参数:

init<S : SequenceType where T == T>(_ s: S)

示例:范围是一个序列:

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

地图采用序列并返回一个数组:

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

自定义序列类型的示例(从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]

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]

答案 1 :(得分:2)

此语法无效:

Array<Int>(count: 100, repeatedValue:(for i in 0...99))

如果您希望将数组保留为let并使用自定义值对其进行初始化,则可以执行以下操作:

let myArray: Array<Int> = {
    var myArray: Array<Int> = []
    for i in 0...99 {
        myArray.append(i)
    }

    return myArray
}()

这意味着myArray将具有在声明之后立即执行的未命名闭包的结果的值。