0

This is the function I tried to use

func merge(inout A: DNode?, inout And B: DNode?) -> DNode? {
    if A == nil && B == nil {
        return nil
    }
    if A == nil {
        return B
    }
    if B == nil {
        return A
    }
    return A!.isLessThan(B!) ? A! : B!
}

Here is how I tried to use the function 'merge'

class Heap {
    var minDNode: DNode?

    func start(inout newNode: DNode) {
        self.minDNode = merge(&self.minDNode, And: &newNode) // error
        // Cannot invoke 'merge' with an argument list of type '(inout DNode?, And: inout DNode)'
    }

    func merge(inout A: DNode?, inout And B: DNode?) -> DNode? {
        ...
    }
}

How can I fix the problem?

Looking at the answer from Swift optional inout parameters and nil,

making

var minDNode: DNode? 

into

var minDNode: DNode? = nil

didn't solve the problem

Community
  • 1
  • 1
Joon. P
  • 2,238
  • 7
  • 26
  • 53

1 Answers1

0

@MartinR makes a good point in the comments: "Why does merge() take inout parameters? The arguments are not modified, so this seems like an unnecessary complication."

The reason for the error is that you have to pass the exact type when using inout, and DNode and DNode? are two different types. newNode needs to be declared as optional because that is what merge is expecting:

func start(inout newNode: DNode?) {
    self.minDNode = merge(&self.minDNode, And: &newNode) // this call now works
}

You probably should rework your code, though, to remove the inout calls where they aren't needed.

vacawama
  • 150,663
  • 30
  • 266
  • 294