Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

(Swift 3)generic parameter T could not be inferred

I am trying to create a function which takes in nested arrays of objects like [1,[2,[3,4],[5,6]]] and return values in single array like this [1,2,3,4,5,6]. I wanted to do it for generic objects so I created a method

func getNestedArray<T>(array:[Any])->[T]?{

    var nestedArray:[T] = []
    for object in array{

        if object is [Any]{
        let neededArray = getNestedArray(array: object as! [Any])
        nestedArray.append(contentsOf: neededArray)
        }
        else if object is T{
            nestedArray.append(object as! T)
        }
        else{
         print("send proper array dumbass")
            return nil
        }
    }
    return nestedArray
}

so if the object is of type T I just append it or if it is of type array I am calling that function again and recursively should give me the correct result but I am getting the error at while calling this function. what am i doing wrong? I am just passing 'Any' type object as '[Any]'. Why does it throw this error?

like image 820
Bharath Reddy Avatar asked Sep 17 '17 15:09

Bharath Reddy


Video Answer


1 Answers

You are not telling the compiler anything about what type neededArray should be. It is only natural that the compiler complains. Judging from the context, I think you want neededArray to be an array of T. So explicitly say the type:

let neededArray: [T] = getNestedArray(array: object as! [Any])

Obviously this does not work because you have not unwrapped the optional. Well, if getNestedArray returns nil that means the array is invalid in the first place, we should probably return nil as well:

guard let neededArray: [T] = getNestedArray(array: object as! [Any]) else { return nil }

Remember to specify the type when you use the method as well!

let result: [Int] = getNestedArray(array: [1, [2, [3, [4]]]])!
like image 88
Sweeper Avatar answered Sep 30 '22 19:09

Sweeper