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()
    }
}
2
  • 3
    Oh, ANOTHER limitation?
    – Sulthan
    Jun 5, 2014 at 19:17
  • In the playground, this does not generate an error. Perhaps it's updated: var value: T? = nil
    – Kokodoko
    Jul 28, 2014 at 14:29
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.

Your Answer

Reminder: Answers generated by Artificial Intelligence tools are not allowed on Stack Overflow. Learn more

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.