Saturday, 15 March 2014

Swift: why use local constant instead of object property? -



Swift: why use local constant instead of object property? -

i'm starting wrap head around swift sense i'm missing here. project template in xcode core info creates local constant refer object property per below. there compelling reason creating constant instead of referring property directly?

func savecontext () { var error: nserror? = nil allow managedobjectcontext = self.managedobjectcontext if managedobjectcontext != nil { if managedobjectcontext.haschanges && !managedobjectcontext.save(&error) { // error handling, etc... } } }

is there compelling reason creating constant instead of referring property directly?

three reasons: brevity/clarity, efficiency, , safety.

using temporary variable in place of property makes code less cluttered, easier read.

it avoids number of superfluous calls property accessor.

finally, it's safer. code retrieves context , compares nil. if used separate property accesses, might different values each time. consider:

if self.managedobjectcontext != nil { if self.managedobjectcontext.haschanges && !self.managedobjectcontext.save(&error) { // error handling, etc... } }

this code pass check nil, managedobjectcontext property change. shouldn't, , changing context willy-nilly cause other problems, if you're going check value it's best maintain using that value , not introduce possibility of inadvertently using other value.

swift

No comments:

Post a Comment