26986

Did not understand process of initialize in swift programming

Question:

I am learning Swfit and i start studied from below link<br /><a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/" rel="nofollow">https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/</a><br /><a href="https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html" rel="nofollow">https://developer.apple.com/library/ios/documentation/Swift/Conceptual/Swift_Programming_Language/Initialization.html </a><br />

I have question regarding Initialization in swift.<br />

<strong>What i understand is as below</strong><br />

1] It works like a constructor for swift classes.<br /> 2] We have to initialize all properties in it.<br /> 3] We have to call init() method of super class.<br /> 4] Before calling init() we have to initialize each and every property.<br /> 5] We can use any member or method of super classes after initialize it.<br />

On the bases of above 5 points I create a classes.<br /> but having a problem because of point 3,4 and 5.<strong>Classes</strong>

/* AdminManagmentSystem - Some class which will consume lots of memory during init */ class AdminManagmentSystem { var adminKey : String init(key:String) { self.adminKey = key; println("Consume lots of memory"); } } /* Person - A base class which can create key. */ class Person { // Some property which will user to create private key. private var privateKey : String = "private" init() { privateKey = "private"; } // function which will calculate key (Comman for all person type) private func calculatekey() -> NSString { return self.privateKey + " key"; } } /* Admin - A sub class which have object of AdminManagmentSystem */ class Admin : Person { // Constant variable let adminmanagmennt : AdminManagmentSystem override init() { self.adminmanagmennt = AdminManagmentSystem(key: ""); // Line1 : Consume lots of memory super.init(); // Line2 : its compalsurry to call super.init var adminKey = super.calculatekey(); // Line3 : We can use any member or method of supper after callign init(). self.adminmanagmennt = AdminManagmentSystem(key: adminKey); // Line4 : Again consume lots of memory } }

<br /><strong>Download project</strong><br /><a href="https://www.dropbox.com/s/afohuxpxxkl5b3c/understandInheritance.zip?dl=0" rel="nofollow">https://www.dropbox.com/s/afohuxpxxkl5b3c/understandInheritance.zip?dl=0</a>

<hr /><strong>Problem</strong><br /> In Line1 and Line4 i have to create object of AdminManagmentSystem which consume a lot memory.

<strong>Question</strong><br /> 1] Why swift make it compulsory to initialize each and every property before calling super.init()?<br /> 2] If I make my property constant why swift allow me to initialize it more then once in init method ?<br /> 3] Why i must have to write override keyword before init() ?<br />

Answer1:

In answer to 1 -

From the Swift Programming Language -

<blockquote>

“As mentioned above, the memory for an object is only considered fully initialized once the initial state of all of its stored properties is known. In order for this rule to be satisfied, a designated initializer must make sure that all its own properties are initialized before it hands off up the chain.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. <a href="https://itun.es/au/jEUH0.l" rel="nofollow">https://itun.es/au/jEUH0.l</a>

</blockquote>

So, until the object is fully initialised, the object is in an undefined state which may be "unsafe", so Swift requires all properties are initialised in phase 1.

In answer to 2

An initialiser function is a special case - its job is to set the object to its initial state, so you can modify 'constant' properties as the object is still in the process of being created -

<blockquote>

“You can modify the value of a constant property at any point during initialization, as long as it is set to a definite value by the time initialization finishes.”

Excerpt From: Apple Inc. “The Swift Programming Language.” iBooks. <a href="https://itun.es/au/jEUH0.l" rel="nofollow">https://itun.es/au/jEUH0.l</a>

</blockquote>

In answer to 3, because you are overriding a method with the same signature as the super class (the no argument init function). The override keyword indicates to the compiler that you know what you are doing. If the compiler silently let you re-declare a super class method you may not realise that you are doing it and get unexpected results.

In answer to the question regarding the consumption of memory, ARC will quickly reclaim the memory that was allocated for the first instance of the object. If this is a performance issue then it is fairly simple to refactor the AdminManagmentSystem class so that there is a function to reset the key on an existing instance -

class Admin : Person { // Constant variable let adminmanagmennt : AdminManagmentSystem override init() { self.adminmanagmennt = AdminManagmentSystem(key: ""); // Line1 : Consume lots of memory super.init(); // Line2 : its compalsurry to call super.init var adminKey = super.calculatekey(); // Line3 : We can use any member or method of supper after callign init(). self.adminmanagmennt.key=adminKey; // You can use a property observer function if a simple assignment isn't enough } }

Recommend

  • UVA714 抄书 Copying Books
  • Serenity Reports Logo Change
  • C# and Active Directory : test if an OU exist
  • JQuery end $.each() loop inside of $.click
  • How can I split a CDockablePane?
  • Upload Image in to server
  • nivo slider overflow issue
  • format of ByteArray returned from C is invalid
  • problem with chinese character
  • Security for Flex app when ssl is not available
  • List categories and their posts from custom post type
  • Updating the input value on button click Jquery
  • nginx - Subdomain as querystring parameter?
  • Can't subscribe to Push notification
  • Obtaining radio button values for use in switch statement in PHP
  • displaying data from multiple tables in datagridview
  • How can I make an image interactive? [closed]
  • Issue with terraform lookup
  • Replacing call to setImageResource() with setImageBitmap to reduce hiccup?
  • Reuse jQuery object from an iframe?
  • How to create 2 svg's on one page?
  • AppEngine Paypal integration giving SSLCertificateError on localhost, using Python
  • Windows 8 Flexboxes - Nesting Flexboxes with overflow enabled
  • java.lang.NumberFormatException: unable to parse '' as integer one more time
  • device tree overlay phandle
  • How to make Rss News Reader application in android …? [closed]
  • Wireshark Display Filter for Unique Source/Destination IP and Protocol
  • How to use Streams api peek() function and make it work?
  • How to decleare char *const argv[] in swift [duplicate]
  • read part of h5 dataset python
  • How to get rgb from transparent pixel in js
  • Computing the discrete fourier transform of audio data with FFTW
  • Using Service Component Runtime
  • WPF custom control and direct content support
  • Write to .csv file with PHP (Commas in Data Error)
  • convert json to excel in java
  • Create/delete users from text file using Bash script
  • ARKit code issue {unknown error -1=ffffffffffffffff error: Task failed with exit 1}
  • Time Complexity of Fibonacci Algorithm [duplicate]
  • How to check if object is null in Java?