dudeman
dudeman

Reputation: 1136

Optional and non-optional not able to be returned from function that returns an optional

I'm working on writing a function that returns what the next node of a tree would be from any node, if doing an in-order traversal. The function has an optional return, which is needed if there is no next node (i.e. we're at the last node). I return both an optional and non-optional from the function and at both places there are compiler errors. Here is the code:

class TreeNode<T> 
{
    var leftChild : TreeNode?
    var rightChild : TreeNode?
    var parent : TreeNode?
    var value : T

    init(withValue:T) {
        self.value = withValue
    }

    func nextInOrderNode<T>() -> TreeNode<T>?
    {
        if var nextNode = rightChild
        {
            while nextNode.leftChild != nil {
                nextNode = nextNode.leftChild!
            }
            return nextNode //error 1
        }
        else
        {
            var nextNode = parent
            var currentNode = self
            while nextNode?.rightChild !== currentNode {
                currentNode = nextNode!
                nextNode = nextNode?.parent
            }
            return nextNode //error 2
        }
    }
}

The errors are:

error 1: Cannot convert return expression of type 'TreeNode<T>' to return type 'TreeNode<T>?'
error 2: Cannot convert return expression of type 'TreeNode<T>?' to return type 'TreeNode<T>?'

I'm not sure what I'm doing wrong here because from what I've seen, it seems like this should work. Any help will be greatly appreciated.

Upvotes: 1

Views: 57

Answers (1)

Martin R
Martin R

Reputation: 539685

The problem is unrelated to optional vs non-optional return values. In

func nextInOrderNode<T>() -> TreeNode<T>?

you introduce a new placeholder type T, locally to this method, which is unrelated to (and hides) the placeholder type T in class TreeNode<T>.

The solution is simple: just remove the placeholder in the method declaration:

func nextInOrderNode() -> TreeNode<T>?

You don't need it here because the scope of T in class TreeNode<T> is the entire class definition, including all methods.

Upvotes: 2

Related Questions