Saturday, 20 September 2014

                       

                             Swift Variables and Constants



Swift Variables and Constants

There are 2 ways to store a value in Swift, as a variable, or a constant. Here is how to create each:



var myNumber  = 45     //Variable let theAnswer = 42     //Constant





That seems simple enough. One might think, var is a type for a Swift variable and let
is the type for a Swift constant, right? Well, while the first may be
true in C#, it is not in Swift. In Swift, these are just keywords
defining whether it is a variable or a constant.


That leads us to the next point, notice the lack of type there?
Swift has implicitly typed stored values. You CAN set the type if you
want, particularly if you do not initialize them, but that is not the
case here. Here, it saw that I wanted to store 45 or 42, and realized,
“Well, 42 is an Int, so ‘theAnswer’ must be storing an Int!”

If you really want to type your variables, you would do so this way:


var theNumber: Double


You must always initialize your let constants, even if you explicitly 
type them.  One reason in Apple’s Swift Language Reference is if you 
wanted a double, but only wanted to type an Int literal, i.e.:


let myExpValue: Double = 29


So it would actually store 29.0 as the value for myExpValue, even though
 you only typed 29.  Just for fun, I tried the opposite, doesn’t work so
 well.  It gives the error, “Type ‘Int’ does not conform to protocol 
‘FloatLiteralConvertible’.”  The error does make sense though.  You have
 to explicitly convert it to work.


Use of Swift Constants

As one would expect, a numeric constant is a constant, so when you try to edit it, a compiler error is shown:
let theAnswer = 42

theAnswer = 21     //Error:  Cannot assign to 'let' value 'theAnswer'




That makes sense, but really seems to limit the use for let stored 
values?  I mean, constants are great and all, but I don’t tend to have 
them all over my code, usually just a few per class, usually for 
stringly typed (not a typo, but a nickname) things like Notifications.
Apple seems to use let all over the place, so why would you want to use constants everywhere?

Convenience Variables

Well, for one, I’m sure most of use have made temporary variables that do not change after their initialization. Something like this example:
CGFloat PADDING_OUTER = 5;

CGFloat textLabelHeight = [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]}].height;

CGFloat detailLabelHeight = [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]}].height;

    

CGFloat totalHeight = PADDING_OUTER + textLabelHeight + detailLabelHeight + PADDING_OUTER;

    

self.tableView.rowHeight = totalHeight;



Sure, we could have done:

self.tableView.rowHeight = 5 + [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleHeadline]}].height + [@"0" sizeWithAttributes:@{NSFontAttributeName : [UIFont preferredFontForTextStyle:UIFontTextStyleCaption1]}].height + 5;



But which is more readable?  PADDING_OUTER, textLabelHeight, 
detailLabelHeight, and totalHeight are all PERFECT places to use let.

Class References

Secondly, the assignment is constant, but are its contents? For reference types (and Classes are reference types), the contents usually aren’t. As such, you could do something like this:
let nf = NSNumberFormatter()

nf.numberStyle = .CurrencyStyle

println(nf.stringFromNumber(7.145))

//Output:  "$7.14"



We never reassign nf to another NSNumberFormatter, but we do change some of its properties, in this case the numberStyle.  This another great use of let in Swift.

Beta 3 Update

There is an exception to the above statement about swift class references. It works that way for most classes, but not for Arrays or Dictionaries. When you set an Array or a Dictionary to a let constant, they are completely immutable. You cannot change their contents like we just did with NSNumberFormatter in the previous example. In the earlier swift Betas, Arrays would allow you to modify an existing index (but not add or remove), but that is no longer the case.
So, just to state it explicitly:
let Arrays and Dictionaries in Swift are completely immutable (cannot change anything).
Swift var Arrays and Dictionaries are mutable (allowing removal, addition, or modification of collection items).


No comments:

Post a Comment