initializing class properties before use in Swift/iOS -
i'm having trouble grasping proper way of instantiating variables need set before object functional may need instantiated after constructor. based on swift's other conventions , restrictions seems there design pattern i'm unaware of.
here use case:
- i have class inherits uiviewcontroller , programmatically create views based on user actions
- i need attach these views class, need retrieve content based on configuration data supplied controller
- i don't care if configuration data passed constructor (in case required) or supplied secondary call object before used
my problem seems both of approaches in bullet 3 seem flawed.
in first case, there 1 legitimate constructor class can called with, yet i'm forced override other constructors , initialize member variables fake values if other constructors never intended used (i'm trying keep these variables let
types based on swift's best practices).
in second case, i'm splitting constructor 2 parts , introduce additional point of failure in case second part fails called prior class being used. can't move second part method that's guaranteed called prior usage (such viewdidload) because still need pass in additional arguments config. while can make sure call initparttwo
manually, i'd prefer have mechanism better groups actual constructor. can't first 1 run , seems there pattern i'm not seeing make cleaner.
update: ended going modified version of pattern matt suggested:
struct thing { let item1: string let item2: string struct config { let item3: string let item4: string } var config:config! { willset { if self.config != nil { fatalerror("tried initialize config twice") } } } init() { self.item1 = ... self.item2 = ... ... } public func phasetwoinit(item3: string, item4: string) { self.item3 = item3 self.item4 = item4 ... } } var t = thing() ... t.phasetwoinit(...) ... // start using t
if initial instance variable property value can't supplied @ object initialization time, usual thing declare optional. way doesn't need initialized class's initializers (it has value - nil
automatically), plus code subsequently can distinguished uninitialized (nil
) initialized (not nil
).
if optional if implicitly unwrapped optional, arrangement need have no particular effect on code (i.e. won't have peppered unwrappings).
if objection forced open door multiple settings of instance variable because must declared var
, close door setter observer:
struct thing { var name:string! { willset { if self.name != nil { fatalerror("tried set name twice") } } } } var t = thing() t.name = "matt" // no problem t.name = "rumplestiltskin" // crash
Comments
Post a Comment