Swift in 24 Hours, Sams Teach Yourself (Sams Teach Yourself -- Hours) by BJ Miller

Swift in 24 Hours, Sams Teach Yourself (Sams Teach Yourself -- Hours) by BJ Miller

Author:BJ Miller
Language: eng
Format: mobi, epub
Publisher: Pearson Education
Published: 2014-11-26T08:00:00+00:00


* * *

Instance Variables

If you are coming from Objective-C, it has instance variables that are the backing value to stored properties. The idea is that you have an instance variable that is of a certain type, and it is what stores values in your instances. On top of that, Objective-C has properties (like we know them in Swift) that provide a layer of abstraction on top of instance variables. Objective-C properties provide safety for instance variables, plus they give clues to the compiler (that you must declare) as to how it should handle memory for that particular instance variable. They also enable you to create custom accessors to assist with getting or setting a property’s instance variable. The widely accepted practice was to label the instance variable with a prefixed underscore to the property name, so that you could identify the instance variable in code apart from the property.

While Objective-C properties are great, they don’t prevent you, the developer, from directly accessing the backing instance variable, which could prove to be unsafe in some cases during execution.

Swift does not allow access to a property’s backingstore, for safety reasons. To enable you to customize a property’s behavior or observe changes to it, Swift provides several methods for that, which we discuss later in this hour.

Lazy Stored Properties

Another type of stored property in Swift is called a lazy stored property. A lazy stored property, or just a lazy property for short, is a property of a struct or class that is known to have a value when it is needed but won’t actually initialize itself until it is first called or accessed. This is useful for situations where you may have a property that has an expensive operation such as loading data from a file on disk, creating or retrieving a lot of data after a particular button is tapped or clicked in an app, or making a lengthy network request, and you don’t want this processing happening at the time of initialization.

To define a property as lazy, simply add the lazy keyword in front of the var introducer. The lazy property must be a var since it may be called after initialization, and all constants must not change after initialization. A lazy property can be assigned an instance of another class, struct, or enum. Listing 14.2 illustrates an example of a lazy stored property.

LISTING 14.2 Lazy Stored Properties

Click here to view code image



Download



Copyright Disclaimer:
This site does not store any files on its server. We only index and link to content provided by other sites. Please contact the content providers to delete copyright contents if any and email us, we'll remove relevant links or contents immediately.