3
推斷我有這使得從嵌套陣列分層陣列的功能。它適用於int數組。錯誤:泛型參數「T」不能在迅速
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] {
感謝您的回答! –
不客氣:) – Yannick