我有从嵌套数组生成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
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]