IneedHelpFromYou February 2016

What is going wrong with my variadic initializer in Swift?

I created a class with an initializer which takes a variadic parameter but it doesn't do what it is supposed to do. I created a variable called start which is a reference to the storted property unteresElement. But somehow it stays "nil" even though I assign it different values. What is going on here?

class Element<T> {
    var content: T
    var next: Element<T>?

    init (_ content: T) {
        self.content = inhalt
    }
}

class LinkedList<T> {
    var lowestElement: Element<T>?

    var isEmpty: Bool {
        return lowestElement == nil
    }

    init (firstElement: T) {
        lowestElement = Element (firstElement)
    }

    init (_ elements: T...) {
        var start = lowestElement

        for element in elements {
            start = Element (element)
            start = start!.next
        }
    }
}

var list1 = LinkedList (5, 91, 20, 3, 60)

print ("\(liste1.lowestElement?.content)")

Answers


R Menke February 2016

There is a mistake in your iteration. You are assigning all values to start, but start is never stored.

Set lowestElement and keep a temporary pointer to the current Element so that you can assign the next attribute with the next current Element.

class Element<T> {

    var content: T
    var next: Element<T>?

    init (_ content: T) {
        self.content = content
    }

}

class LinkedList<T> {

    var lowestElement: Element<T>?

    var isEmpty: Bool {
        return lowestElement == nil
    }

    init (firstElement: T) {

        lowestElement = Element(firstElement)

    }

    init (_ elements: T...) {

        var current : Element<T>!

        for element in elements {

            if lowestElement == nil {
                lowestElement = Element(element)
                current = lowestElement!
            } else {
                let next = Element(element)
                current.next = next
                current = next
            }
        }
    }
}

var list1 = LinkedList (5, 91, 20, 3, 60)

print ("\(list1.lowestElement?.content)")

Post Status

Asked in February 2016
Viewed 1,233 times
Voted 14
Answered 1 times

Search




Leave an answer