Tuesday 15 March 2011

swift - Implementing an enum ForwardIndexType -



swift - Implementing an enum ForwardIndexType -

i have been struggling implement forwardindextype protocol enum, in particular handling of end case (i.e lastly item without successor). protocol not covered in swift language book.

here simple example

enum threewords : int, forwardindextype { case one=1, two, 3 func successor() ->threewords { homecoming threewords(rawvalue:self.rawvalue + 1)! } }

the successor() function homecoming next enumerator value, except lastly element, fail exception, because there no value after .three

the forwardtypeprotocol not allow successor() homecoming conditional value, there seems no way of signalling there no successor.

now using in loop iterate on closed range of possible values of enum, 1 runs problem end case:

for word in threewords.one...threewords.three { print(" \(word.rawvalue)") } println() //crashes error: fatal error: unexpectedly found nil while unwrapping optional value

swift inexplicably calls successor() function of end value of range, before executing statements in loop. if range left half open threewords.one..<threewords.three code executes correctly, printing 1 2

if modify successor function not seek create value larger .three this

func successor() ->threewords { if self == .three { homecoming .three } else { homecoming threewords(rawvalue:self.rawvalue + 1)! } }

then loop not crash, misses lastly iteration, printing same if range half open 1 2

my conclusion there bug in swift's loop iteration; should not phone call successor() on end value of closed range. secondly, forwardindextype ought able homecoming optional, able signal there no successor value.

has had more success protocol ?

indeed, seems successor called on lastly value.

you may wish file bug, work around add together sentinel value deed successor.

swift enums

No comments:

Post a Comment