Show Menu

Need an iOS Developer?

Submit your 30 day Job Listing for FREE

How do you store data in a program? Or, How do you store data in Swift for your iOS Application. Well, you store them in variables, but you already knew that didn’t you? Here is my first post about Swift variables, where we discuss their Swift Variable declaration and Swift Variable definition. In particular, we will mostly be discussing the concept of Swift variables and Swift constants.

Here are some awesome Swift Resources to help you along your swift development Journey.

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).

Conclusion

In this post, I have often used the term “stored value” to refer to variables and constants, as opposed to saying variable variables and variable constants, (suddenly I am reminded of “Mario Mario” and “Luigi Mario” from the Mario Bros. Movie). For future posts though, unless I am talking about the differences again, I will probably just refer to them both as variables for the sake of simplicity. I will refer to constants as such when I need to specify the difference, but more often than not, I will probably refer to our NSNumberFormatter variable, even if I do make it a constant let, in the code.

having issues?

We have a Questions and Answer section where you can ask your iOS Development questions to thousands of iOS Developers.

Ask Question

FREE Download!

Get your FREE Swift 2 Cheat Sheet and quick reference guide PDF download when you sign up to SwiftMonthly


Sharing is caring

If you enjoyed this tutorial, please help us and others by sharing using one of the social media buttons below.


Written by:

Nick Hanan is learning Objective-C and wants to help others on the same journey. He started the Coding Explorer Blog to chronicle what he is learning as he explores the Objective-C landscape. Check out his blog for information from a beginners perspective

Comments

comments