错误:无法在swift中推断泛型参数'T'

时间:2017-10-19 14:16:18

标签: ios arrays swift algorithm generics

我有从嵌套数组生成平面数组的函数。它适用于int数组。

let array: [Any] = [1, 2, [3]]

func makeFlatArray(_ array: [Any]) -> [Int] {
    var flatArray = [Int]()
    for item in array {
        if let item = item as? Int {
            flatArray.append(item)
        } else if let item = item as? [Any] {
            let result = makeFlatArray(item)
            flatArray += result
        }
    }
    return flatArray
}

但我想让它变得通用,我在尝试时遇到了错误。

func makeFlatArrayGeneric<T>(_ array: [Any]) -> [T] {
    var flatArray = [T]()
    for item in array {
        if let item = item as? T {
            flatArray.append(item)
        } else if let item = item as? [Any] {
            let result = makeFlatArrayGeneric(item)
            flatArray += result
        }
    }
    return flatArray
}

错误:

Playground execution failed:

error: FlatNestedArraysExample.playground:22:26: error: generic parameter 'T' could not be inferred
            let result = makeFlatArrayGeneric(item)
                         ^

FlatNestedArraysExample.playground:16:6: note: in call to function 'makeFlatArrayGeneric'
func makeFlatArrayGeneric<T>(_ array: [Any]) -> [T] {

2 个答案:

答案 0 :(得分:6)

你必须告诉编译器T的类型。

func makeFlatArrayGeneric<T>(_ array: [Any]) -> [T] {
    var flatArray = [T]()
    for item in array {
        if let item = item as? T {
            flatArray.append(item)
        } else if let item = item as? [Any] {
            let result: [T] = makeFlatArrayGeneric(item)
            flatArray += result
        }
    }
    return flatArray
}

let array: [Any] = [1, 2, [3], [4, [5]]]
let items: [Int] = makeFlatArrayGeneric(array) //[1, 2, 3, 4, 5]

解决问题的更实用的方法。

extension Array {
    func flatten() -> Array<Element> {
        return self.flatMap({ element -> [Element] in
            if let array = element as? Array {
                return array.flatten()
            } else {
                return [element]
            }
        })
    }
}

let items: [Int] = array.flatten() //[1, 2, 3, 4, 5]

答案 1 :(得分:1)

你必须做些什么来快速了解什么是T,一种方法是将返回值分配给类型已知的变量:

let result: [T] = makeFlatArrayGeneric(item)

另一种方法是将类型作为参数传递:

func makeFlatArrayGeneric<T>(_ array: [Any], type: T.Type) -> [T] {
    var flatArray = [T]()
    for item in array {
        if let item = item as? T {
            flatArray.append(item)
        } else if let item = item as? [Any] {
            let result = makeFlatArrayGeneric(item, type: type)
            flatArray += result
        }
    }
    return flatArray
}

并称之为:

makeFlatArrayGeneric(yourArray, type: Int.self)