ios - How to set an object to nil in Swift? -


i'm implementing simple stack in swift. ran unexpected behavior while writing pop() , i'm hoping can explain why happening.

i wrote original pop function this:

class func pop(inout head : node)->node? {     var currentnode : node? = head      while currentnode!.next != nil {         currentnode = currentnode!.next!     }      var lastnode = currentnode     currentnode = nil     return lastnode } 

basically, i'm finding tail of linked list , setting object nil. however, item retained, can see in console output:

//traversing initial list

10 11 12 13 14

popped: 14

//list after popping

10 11 12 13 14

as can see, 14 not removed, though returned pop() function correctly.

now, second thought set previous node's next pointer nil, edited above function read this:

class func pop(inout head : node)->node? {     var currentnode : node? = head     var previousnode : node = head      while currentnode!.next != nil {         previousnode = currentnode!         currentnode = currentnode!.next!     }      var lastnode = currentnode     previousnode.next = nil     currentnode = nil     return lastnode } 

this prints out expected output console this:

//traversing initial list

10 11 12 13 14

popped: 14

//list after popping

10 11 12 13

my question this:

shouldn't setting currentnode nil mean previousnode.next pointing nil? why have explicitly set previousnode.next = nil ?

thank insight can provide.

solution:

here solution came with

class func pop(inout head : node?)->node? { var currentnode : node? = head var previousnode : node? = head  if currentnode?.next == nil {     var lastnode = currentnode     head = nil     return lastnode  }  while currentnode!.next != nil {     previousnode = currentnode!     currentnode = currentnode!.next! }  var lastnode = currentnode previousnode!.next = nil return lastnode } 

i needed treat last case differently , set head nil

why setting currentnode nil not delete thing it's pointing to? let me try use analogy: imagine variable (if it's instance of class) kind of finger. can use point @ things. pointing finger @ tree, cutting off finger, won't cut down tree.

in real world, pointers pointing memory. when set pointer null, not destroying whatever pointing to. however, if set pointers object null, have no more way of accessing , lost. (also arc or garbagecollection gonna come around , remove object memory, that's different story).


Popular posts from this blog

c# - ODP.NET Oracle.ManagedDataAccess causes ORA-12537 network session end of file -

matlab - Compression and Decompression of ECG Signal using HUFFMAN ALGORITHM -

utf 8 - split utf-8 string into bytes in python -