Swift: compile time error with optional chaining and nil-coalescing

I have a weird issue with optional chaining and nil-coalescing in Swift. Can someone please explain why the following code won't compile:

class A<T> {
    var val: T
    var x: A<T>?
    var y: A<T>?
    init(t:T){
        val = t
    }
    func test() -> [T] {
        return (self.x?.test() ?? []) + [val] + (self.y?.test() ?? [])
    }
}

      

But when writing

func test() -> [T] {
    return (self.x?.test() ?? []) + ([val] + (self.y?.test() ?? []))
}

      

He does? The error says:

Cannot convert value of type '[T]?' to expected argument type '[_]?'

      

To me it looks a lot like a compiler error.

+3


source to share


1 answer


The inferring type is complex with complex expressions. What [_]

usually means that the type is unknown cannot be inferred. Simplifying the expression solves the problem 99% of the time:

class A<T> {
    var val: T
    var x: A<T>?
    var y: A<T>?
    init(t:T){
        val = t
    }
    func test() -> [T] {
        let xResult = self.x?.test() ?? []
        let yResult = self.y?.test() ?? []

        return xResult + [val] + yResult
    }
}

      

Another 99% of the time, enter inference problems can be solved by explicitly specifying the type:



return (self.x?.test() as [T]? ?? []) + [val] + (self.y?.test() ?? [])

      

You have found a workaround yourself. This parenthesis workaround removes a certain number of types that infer the path.

Reported SR-4309

+3


source







All Articles