Search code examples
swiftgenericsswift2introspection

Swift 2 Introspection


I am converting some "old" Swift code to Swift 2.0, and I run into an error I cannot get rid of.
My function receives an Array of a type (whatever), and returns a new Array of the same type.

This code no longer works in Swift 2.0:

func makePattern1<T>(var list: Array<T>) -> Array<T> {
    let theType = list.dynamicType
    var result = theType()
    for i in 1..<list.count {
        result.append(list[i])
        result.append(list[i-1])
    }
    return result
}

giving the error message: "Initializing from a metatype value must reference 'init' explicitly".

Correcting the code with: var result = theType.init() gives a "Type of expression is ambiguous without more context" error.

What am I missing?


Solution

  • This code is written in Swift 2.1 and does use the map function as you requested in the comments.

    func makePattern1<T>(list: [T]) -> [T] {
        return list[0..<list.count-1]
            .enumerate()
            .map { [list[$0.index+1], list[$0.index]] }
            .flatten()
            .map { $0 as T }
    }
    

    Update #1

    (thanks Martin R)

    func makePattern1<T>(list: [T]) -> [T] {
        return list[0..<list.count-1]
            .enumerate()
            .flatMap { [list[$0.index+1], list[$0.index]] }
    }
    

    Update #2

    func makePattern1<T>(list: [T]) -> [T] {
        return [Int](1..<list.count).flatMap { [list[$0], list[$0-1]] }
    }
    

    Test

    makePattern1([1,2,3,4,5]) // > [2, 1, 3, 2, 4, 3, 5, 4]