Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Assigning `nil` value to a generically typed variable in Swift

Tags:

swift

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?

like image 1000
Jason Kim Avatar asked Jun 05 '14 19:06

Jason Kim


1 Answers

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()
    }
}
like image 140
MagerValp Avatar answered Nov 15 '22 10:11

MagerValp