A simple variable in swift -
i know basic don't this. want set variable class (uiview) , , later set value, give me error on init method :
var cellsize:cgfloat override init (frame : cgrect) { super.init(frame : frame) cellsize=self.frame.size.width
then trying :
var cellsize:cgfloat cellsize=1.0 super.init(frame : frame) cellsize=self.frame.size.width
which compile, , seems wrong . 1 working :
var cellsize:cgfloat=1.0 override init (frame : cgrect) { super.init(frame : frame) cellsize=self.frame.size.width
which works seems wrong because i'v told him cgfloat
why if tell complier cgfloat
, won't let me continue without setting value ?
all class variable or instance variable should initialised before class instantiated. reason instance of class need class variable , instance variable , without value leads chaos. there need initialise it.
swift on other hand provide exception above said concept providing optionals nothing optional class or instance variable, have insure these variables initialised later in class before using it. optional variables represented exclamation mark suffix i.e var cellsize:cgfloat!
coming question first code -
var cellsize:cgfloat override init (frame : cgrect) { super.init(frame : frame) cellsize=self.frame.size.width
you haven't provided value or in other words have not initialised hence doesn't compile ( cellsize need value before super.init(frame:frame) called.
on second block -
var cellsize:cgfloat cellsize=1.0 super.init(frame : frame) cellsize=self.frame.size.width
it compiles same reason gets value before calling super.init(frame:frame). why seems wrong? gives cell size initial value of 1.0 , later override value self.frame.size.width doing cellsize=self.frame.size.width
third work same reason because giving initial value @ declaration itself.
the right way create cellsize optional purpose assume using -
var cellsize:cgfloat! // doing tell compiler hey! not initialising , guarantee provide value before use , if fail please spit error. override init (frame : cgrect) { super.init(frame : frame) cellsize=self.frame.size.width }
hope clear.
br
Comments
Post a Comment