ios - Are class-based Swift Constants Forced to be Optional -


i'm new swift development, apologise if silly question - having read apple's guide, surprised behaviour have come across (and little miffed).

i creating simple class defines number of uninitialised constants @ beginning of class. when class initialised, values set. seems though cannot unless declare constants optional, though not optional , set in constructor. example:

class testclass {     private let urladdress:string      init(urladdress: string) {         self.urladdress = geturladdresswithproto("http", urladdress:urladdress)     }      func geturladdresswithproto(proto: string, urladdress:string) -> string {         return "\(proto)://\(urladdress)/"     } } 

the function geturladdresswithproto returns non-optional string xcode throws error: error: variable 'self.urladdress' used before being initialized

does have thoughts firstly on why case , if there suitable alternative declaring constants optional?

the compiler wants tell you not allowed call function before non-optional variables initialized. error messages not obvious.

swift prevents use of instances in inconsistent state. swift not know function call doesn't rely on internal state, can't call instance functions before init done @ all.

you have couple of options, besides marking variable optional.

  • turn function class function. since class functions not bound instance can call them before init of instance done
  • move code function initializer
  • turn variable implicitly unwrapped optional. (i.e. let urladdress: string!). can use variable if non-optional variable. make sure set during init. if while nil program abort.

depending on real code last 1 viable option.


Comments

Popular posts from this blog

matlab - "Contour not rendered for non-finite ZData" -

delphi - Indy UDP Read Contents of Adata -

javascript - Any ideas when Firefox is likely to implement lengthAdjust and textLength? -