Wednesday, 15 April 2015

Swift - Can't convert BST node to generic -



Swift - Can't convert BST node to generic -

when implemented concrete type, binary search tree node works fine in playground:

class node { var data: int var leftchild: node? var rightchild: node? init(data: int){ self.data = info } } allow n = node(data: 42) // {data 42 nil nil}

when seek create generic, xcode crashes , burns:

class genericnode<t: comparable> { var data: t var leftchild: genericnode? var rightchild: genericnode? init(data: t){ self.data = info } } allow g = genericnode<int>(data: 42)

when entered line-by-line, xcode survives until come in actual assignment in init. tried specifying <anyobject: comparable>, apparently adding constraints anyobject not allowed. how 1 create suitably constrained generic containers in swift?

definitely bugs here. code doesn't crash:

class genericrootclass { } class genericnode<t: genericrootclass t : comparable> { allow data: t var leftchild: genericnode<t>? var rightchild: genericnode<t>? init(data: t) { self.data = info } }

but remove genericrootclass in type constraint or alter or anyobject, xcode crashes.

as aside: you'll note couple other changes in code:

the data property should immutable. the kid nodes should of type genericnode<t>, can compare against data. (the compiler have pointed 1 out, if survive long enough.)

something simple as

class genericrootclass<t> { var data: t? }

is able crash xcode 6 beta 2. appears generic classes aren't working @ moment.

generics swift

No comments:

Post a Comment