12

I think var value: T = nil is causing error below because XCode can't convert nil value to the generic type T.

class Node<T> {
    var value: T = nil
    var next: Node

    init(value: T) {
        self.value = value
        self.next = Node()
    }

    init() {
        self.next = Node()
    }
}

The error message reads

Could not find an overload for '_coversion' that accepts the supplied arguments

Is there a way to assign nil value to a variable in Swift?

2 Answers 2

23

You need to declare the variable as optional:

var value: T? = nil

Unfortunately this currently seems to trigger an unimplemented compiler feature:

error: unimplemented IR generation feature non-fixed class layout

You can work around it by declaring T with a type constraint of NSObject:

class Node<T:NSObject> {
    var value: T? = nil
    var next: Node

    init(value: T) {
        self.value = value
        self.next = Node()
    }

    init() {
        self.next = Node()
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Oh, ANOTHER limitation?
In the playground, this does not generate an error. Perhaps it's updated: var value: T? = nil
0

Try using

var value: T? = nil

The question mark makes the variable an optional, meaning that it can either have a value or be nil.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.