当前位置 : 主页 > 手机开发 > ios >

ios – 错误:无法在swift中推断泛型参数’T’

来源:互联网 收集:自由互联 发布时间:2021-06-11
我有从嵌套数组生成flatted数组的函数.它适用于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(it
我有从嵌套数组生成flatted数组的函数.它适用于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] {
你必须告诉编译器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]
网友评论