generics - What is going wrong with my variadic initializer in Swift? -
i created class initializer takes variadic parameter doesn't supposed do. created variable called start reference storted property untereselement. somehow stays "nil" though assign different values. 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 element in elements { start = element (element) start = start!.next } } } var list1 = linkedlist (5, 91, 20, 3, 60) print ("\(liste1.lowestelement?.content)")
there mistake in iteration. assigning values start
, start
never stored.
set lowestelement
, keep temporary pointer current element
can assign next
attribute 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>! 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)")
Comments
Post a Comment