Fluid Layouts with Auto Layout, Size Classes, Spacer Views, and Constraint Priorities

I came across a problem the other day with the “compact x any” size class in iOS 8 & Xcode 6. I was creating a layout for the size class which is supposed to cover the iPhone 4S 3.5-inch screen all the way up to the iPhone 6 4.7-inch screen. However, this became difficult to do well because what looked good on a small screen (like the 3.5-inch) did not look good on the large screen (4.7-inch screen). Or what looked good on a bigger screen, the content did not fit on the smaller screen.

So, I started playing around with how to create a fluid layout to make this work and it turned out to be much more difficult than I anticipated. So, I thought I’d share an example of how I did it.

I’m going to show you how to create a fluid layout using Xcode 6 in the compact-any size class which works for all compact width layouts such as the 3.5-inch iPhone 4S all the way up to the 4.7-inch iPhone 6. I will show you how to create a fluid layout for a form for this size class so that, for example, when we’re on the iPhone 3.5 inch, it’s a compact form (see pic below)fluid layout initial setup, but when we go up to 4.7-inch iPhone 6, the form will expand and fill the entire screen (see pic below). fluid_layout_iphone_6_size We will use spacer views to make this form expand out to fill this entire screen.

In this form, you can see we have some labels and then some text fields. But what you need to know is that we also have an encompassing view surrounding each of those.encompassing views So, each of these fields and labels has an encompassing view which then has some constraints on it to their neighboring-sibling views and labels.

Ok, now that you know that. I’ll show you how we can add spacer views to make this form fluid.

Auto Layout Spacer Views

First, select all of the labels and text fields (and their encompassing views) and slide them down to make room for a spacer view underneath the header label.fluid layouts create space From the object collection in the right menu, search for a plain “view”. Scroll down and select a plain “view” from the collection and drag and drop it onto the storyboard.select view We’re going to need re-size this. We’re going to keep it 200 points wide. Go up to the size inspector and change the height to just 10. change height of spacer viewReposition the view just below the first label.reposition spacer view Now, we need to set up our constraints.

Auto Layout Constraints

The first constraint that we’re going to set up is a vertical constraint to the first label. So, hold down ctrl + click and drag to the first label and select “vertical spacing” create vertical spacing constraint Next, set up a center horizontally container constraint. This is going to make the spacer view center horizontally with the rest of these labels and fields. Create another vertical spacing constraint with the next view that encompasses the first label and text field. create_constaint_with_encompassing_view Then, create constraints for the width and the height. autolayout_create_height_and_width_constraint

So now, we have all the constraints for this spacer view, but we need to change the constants on some of the constraints. To do that, select the spacer view and then select the size inspector from the menu of the right.

The first constant we’re going to change is the first vertical spacing constraint. Select the constraint and change the constant to zero.change_autolayout_constraint_constant Then, change the bottom space constraint to zero as well. And you can see now that all the space that exist now between the first label and the next encompassing view is the height of our spacer view.

Auto Layout Contraint Priorities

The last thing we need to do for this spacer view is set the priority of this height constraint. To change the priority, select the height constraint and hit “edit” and under the priority selection, select 750.change_auto_layout_constraint_priority So, slightly less priority than all the other constraints. And that’s it, that’s all we need to do for this first spacer view.

So, copy the spacer view by holding down the option key and dragging it down below the first form field. copy_and_reposition_second_spacer_view

Now, we need to do the same thing with this spacer view as we did with the first one. Set a vertical constraint to the encompassing view of the first form field. Then, add a vertical spacing constraint to the next encompassing view of the next form field. Add a constraint to make sure it’s centered horizontally and it’s all set, it should have already copied over the width and height constraints.

We need to change the constants on the constraints once again. Select the spacer view and go to the size inspector and change the vertical spacing constraints’ constants to zero.

We also need to do something a little bit different with the height constraint. We’re actually going to remove the height constraint. Open up the document outline for the storyboard. open_document_outline Go back over to our height constraint and select it and that will show selected in the document outline, so we’ll select it and just hit delete and remove that.remove_auto_layout_height_constraint So, now that constraint is gone. Select the second spacer view again, and hold down ctrl, click and drag and select the first spacer view and set the constraint as equal heights. set_auto_layout_equal_heights_constraint

The idea here is that we’ll create the spacer views that will then expand equally out as the screen gets larger. So, we don’t want them to be different heights or expand the different sizes, we want them all to be equal size. So, we’re going to set them as equal heights. And that’s it! That’s all we need for this second spacer view.

You will need to setup a spacer view in between each encompassing view of the form. Because of the rest of the spacer views are pretty much the same as the first and the second one, I’m just going to go ahead and skip to the end of this so that all the spacer views will be set up. I will show you the last step that we need to do in order to create our fluid layout. Here’s what the layout looks like with all the spacer views setup. spacer_views_all_setup

So, the last step we need to do, select the “sign up” button and control drag and create one more constraint by selecting the controller’s view and select “bottom space to bottom layout guide”. add_auto_layout_bottom_space_constraint So now we have created this constraint for this button. We have this constraint now, but we want the “sign up” button constrained, so that’s a little bit closer to the bottom of the screen. The way we can do that is selecting the new constraint and updating this constant to be a smaller number than 209, that’s automatically set to right now. Set the constant on this constraint to 50. hange_auto_layout_constraint_constant_to_50 You can see the form now expands. And you can see that is expanding because the height of this spacer views is expanding as well and they’re expanding equally. And that’s because the constraint priority that we set up earlier for the height of the spacer view. fluid_form_with_spacer_views_with_background_color

Because that constraint has a lower priority than the rest of the constraints that were set up, the constraint breaks when it expands and contracts for the different sizes of the screens. If your spacer views have a background color, you can go ahead and remove the color from this spacer views. Now, you can see how the form expands and contracts in the different fields have equal spacing in between them, it expands and contracts to fill out the different screens. fluid_form_with_spacer_views_without_background_color

So, that’s it! That’s how we can create a fluid layout using spacer views and constraint priorities in Xcode 6 with size classes. So if you have any questions, feel free to leave a comment and I will try to answer them.

More to Learn

If you have found this information useful and would like to learn about Swift, please sign up for the Swift newsletter below and I will send you updates when new posts and videos become available. You’ll also receive access to my swift tutorial video “Advanced Swift Arrays”.

How to Use Swift Computed Properties to Create a Simple Goal Tracker Class

This is the fourth Swift tutorial and video in a series I’m doing on Swift development.

Source code examples are available on GitHub

In this tutorial, we’re going to take a look at Swift computed properties and how they work. We’re going to create a very simple GoalTracker class. All our GoalTracker class is going to do is track our progress through something, i.e. how many miles or kilometers we’ve run, or how many pages we’ve read in a book, etc. but we’re going to keep it pretty simple.

Setup GoalTracker Swift Class

First, let’s create a class called GoalTracker.

class GoalTracker {
}

Next, on our GoalTracker class, we’re going to create a variable property called goal and give it a type of Double and we’re going to initialize it to zero.

class GoalTracker {
  var goal: Double = 0.0
}

Next, we’re going to create another variable property. Let’s call it unitsCompleted. It’s also going to be a Double and we’ll also initialize it to zero.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
}

##Swift Read-only computed properties
Finally, let’s create another variable property called unitsLeft and it will be a Double but instead of initializing it to zero, we’re going to use curly braces and declare this as a read-only computed property. Now, the way read-only computed properties work, all we have to do is return an instance of a double type. In this case, to determine units left, all we need to do is return the goal minus the units completed.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
  var unitsLeft: Double {
    return goal - unitsCompleted
  }
}

That’s it. We can check this by declaring a variable called goalTracker and then we’ll just initialize a GoalTracker. We can then set the goal property of the goalTracker variable. In this case, we’ll set it to 20.0.

var goalTracker = GoalTracker()
goalTracker.goal = 20.0

Now, if we now take our GoalTracker and we set our units completed property to 5.0 and then we can print our GoalTracker unitsLeft property.

goalTracker.unitsCompleted = 5.0
println(goalTracker.unitsLeft) //15.0

Great, it works! What if we wanted to set unitsLeft and determine our unitsCompleted? Well, we can do that by reformatting the unitsLeft computed property.

Swift Getter and Setter

First, we’re going to declare a getter function on the computed property. Every computed property in swift can have a getter and a setter. We can create a getter by simply wrapping our original expression in a “get” function.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
  var unitsLeft: Double {
    get {
      return goal - unitsCompleted
    }
  }
}

We’ll declare the setter which takes a parameter called “newUnitsLeft”. This parameter is provided automatically when we declare a setter in a Swift computed property. All it does is prepend a “new”” to the front of whatever property we’ve declared. In this case, it’s just newUnitsLeft. Given newUnitsLeft, we can determine the unitsCompleted. We simply set unitsCompleted equal to the goal minus the newUnitsLeft parameter. That’s it.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
  var unitsLeft: Double {
    get {
      return goal - unitsCompleted
    }
    
    set(newUnitsLeft){
      unitsCompleted = goal - newUnitsLeft
    }
  }
}

Now, if we change unitsCompleted to unitsLeft and then we get our units completed, you can see that we can now determine our units completed from our units left if we change that to 8.3, now you can see that unitsCompleted is updated to 11.7.

goalTracker.unitsLeft = 8.3
println(goalTracker.unitsCompleted) //11.7

Percentage Completed

But let’s say we wanted to take this one step further and we wanted to find out how much we’ve completed as a percentage, how would we do that? We can do that by declaring another computed property on our GoalTracker class. Let’s declare a variable property called percentageCompleted. This is going to be a double and a computed property.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
  
  var percentageCompleted: Double {
  }
  
  var unitsLeft: Double {
    get {
      return goal - unitsCompleted
    }
    
    set(newUnitsLeft){
      unitsCompleted = goal - newUnitsLeft
    }
  }
}

We’re going to use a getter and a setter. In this case, we’ll declare the getter first. To determine the percentage completed, all we need to do is return the unitsCompleted divided by the goal. We’ll also want to format our percentageCompleted because both dividing goals and unitsCompleted will result in a decimal, so if we do multiply it by 100, we’ll get a percentage.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
  
  var percentageCompleted: Double {
    get {
      return unitsCompleted/goal * 100
    }
  }
  
  var unitsLeft: Double {
    get {
      return goal - unitsCompleted
    }
    
    set(newUnitsLeft){
      unitsCompleted = goal - newUnitsLeft
    }
  }
}

In the setter, we’re going to pass in the new percentageCompletedParameter that’s provided by Swift and then set unitsCompleted equal to the goal times the newPercentageCompleted divided by 100. This will allow us to input the percentage completed as a whole number instead of having to input it as a decimal.

class GoalTracker {
  var goal: Double = 0.0
  var unitsCompleted: Double = 0.0
  
  var percentageCompleted: Double {
    get {
      return unitsCompleted/goal * 100
    }
    
    set(newPercentageCompleted){
      unitsCompleted = goal * (newPercentageCompleted/100)
    }
  }
  
  var unitsLeft: Double {
    get {
      return goal - unitsCompleted
    }
    
    set(newUnitsLeft){
      unitsCompleted = goal - newUnitsLeft
    }
  }
}

Now, we can test it out. If we set 8.3 as our unitsLeft, then our percentageCompleted is 58.5%. If we wanted to see percentageCompleted if we pass in 10.0 for our units completed, the percentage is 50%. We can also change this to say, 1.2 and the percentageCompleted is 6%. Our percentage completed is working as intended.

goalTracker.unitsLeft = 8.3
println(goalTracker.percentageCompleted) //58.5
goalTracker.unitsCompleted = 10.0
println(goalTracker.percentageCompleted) //50.0
goalTracker.unitsCompleted = 1.2
println(goalTracker.percentageCompleted) //6.0

If we wanted to check our setter, we just take our percentage completed property and we set it equal to 2.46% and then the units left would be 17.54.

goalTracker.percentageCompleted = 2.46
println(goalTracker.unitsLeft) //17.54

More to Learn

This is just a brief overview of how swift computed properties work. If you have found this information useful and would like to learn more about Swift, please sign up for the Swift newsletter below and I will send you updates when new posts and videos become available. You’ll also receive access to my swift tutorial video “Advanced Swift Arrays”.

How to Create a NSNumberFormatter Singleton in Swift

This is the third post and screencast in a series I’m doing on Swift development.

Source code examples are available on GitHub

Singletons are a popular design pattern in programming. If you are new to Swift, you may be wondering how you can create singletons in Swift. In Objective-C, you might have tried Grand Central Dispatch‘s dispatch_once to create a singleton. Well, the other day, I came across a situation in Swift that I thought would be a good example of using a singleton.

I needed to use the NSNumberFormatter class to change an integer like “15” into a currency like “$15.00” for a table view I was displaying. Because initializing an NSNumberFormatter can be an expensive operation, I didn’t want the performance of the app to be affected by this, especially if I was going to be using the same NSNumberFormatter configuration throughout the app. So, I decided to use a singleton.

Now, there’s a great stack overflow post all about the different ways to create a Singleton in Swift, however, it doesn’t provide an in-depth practical example and since NSNumberFormatter is a class that gets used a lot, I thought I would share an example of using these patterns with this class. Ok, let’s get started.

First, we’re going to import the Foundation library.

import Foundation

Then, we’re going to declare a class called CurrencyFormatter, which is going to inherit from the NSNumberFormatter class.

class CurrencyFormatter: NSNumberFormatter {

In order to inherit from the NSNumberFormatter class, you have to implement a required init function. All we do is just call the same function with super, and then the pass the aDecoder parameter to the function. This isn’t important to our problem but it’s required, so you can mostly ignore it.

required init(coder aDecoder: NSCoder) {
  super.init(coder: aDecoder)
}

Override Init()

Now, we are going to override the standard “init” function, so we can set some default values on initialization. Inside the init function, first we need to call the “super.init” function. Next is code to make the currency formatting work correctly.

override init() {
  super.init()
  self.locale = NSLocale.currentLocale()
  self.maximumFractionDigits = 2
  self.minimumFractionDigits = 2
  self.alwaysShowsDecimalSeparator = true
  self.numberStyle = .CurrencyStyle
}

Type Property Constants – version 1.2 or above

If you’re using Swift 1.2 or above, we’re almost done. All we need to do is declare a type constant property. To declare a type constant property on a class, we use the “static let” keywords and call it sharedInstance and then we’ll initialize it to an instance of our CurrencyFormatter class.

static let sharedInstance = CurrencyFormatter()

Now our singleton should be ready. Here’s the final code.

import Foundation

class CurrencyFormatter: NSNumberFormatter {
  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }
  
  override init() {
    super.init()
    self.locale = NSLocale.currentLocale()
    self.maximumFractionDigits = 2
    self.minimumFractionDigits = 2
    self.alwaysShowsDecimalSeparator = true
    self.numberStyle = .CurrencyStyle
  }
  
  // Swift 1.2 or above
  static let sharedInstance = CurrencyFormatter() 
}

NSNumberFormatter has a method called “#stringFromNumber” and all we need to do is call “#stringFromNumber” on the sharedInstance singleton and pass in the number. So, we’ll just pass in 20 and then we’ll unwrap the optional so we can see it.

println(CurrencyFormatter.sharedInstance.stringFromNumber(20)!) //$20.00

You can see now that our number is formatted to $20.00 and if we copy this and change it to 50, you can see it works as well.

println(CurrencyFormatter.sharedInstance.stringFromNumber(20)!) //$20.00
println(CurrencyFormatter.sharedInstance.stringFromNumber(50)!) //$50.00

Before Swift 1.2, Class Variable Properties and Nested Structs

If you’re using a version of Swift below 1.2, you can’t actually declare type constants on reference types like classes, so we’ll have to do this a different way. Go ahead and remove the type constant we created.

This time, we’re going to declare a class variable property, which we’ll call our sharedInstance. But instead of initializing it, we’re going to declare it as a CurrencyFormatter type and then we’re going to declare this class variable as a read-only computed property.

class var sharedInstance: CurrencyFormatter {
}

A computed property means instead of storing a value for this property, it just computes it every time that it’s called. In this case, it means we have to return an instance of CurrencyFormatter every time that this property is called. However, we can make it return the same instance by creating a singleton.

First, we’re going to declare a struct inside of this property. We declare a struct called Static.

class var sharedInstance: CurrencyFormatter {
  struct Static {
  }
}

Structs in Swift are value types and in versions below 1.2, value types can have type constants which will allow us to create a Singleton of our CurrencyFormatter class. We’re going to declare it a type constant using static let, and then call it instance and then initialize it to an instance of our currency formatter class.

class var sharedInstance: CurrencyFormatter {
  struct Static {
    static let instance = CurrencyFormatter()
  }
}

Then we need to return our Static.instance property (and singleton) at the end of the computed property.

class var sharedInstance: CurrencyFormatter {
  struct Static {
    static let instance = CurrencyFormatter()
  }
  return Static.instance
}

Here’s the final code using the class variable and nested struct.

import Foundation

class CurrencyFormatter: NSNumberFormatter {
  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder)
  }
  
  override init() {
    super.init()
    self.locale = NSLocale.currentLocale()
    self.maximumFractionDigits = 2
    self.minimumFractionDigits = 2
    self.alwaysShowsDecimalSeparator = true
    self.numberStyle = .CurrencyStyle
  }
  
  class var sharedInstance: CurrencyFormatter {
    struct Static {
      static let instance = CurrencyFormatter()
    }
    return Static.instance
  }
}

And now our numbers are formatted again, so we’re getting the correct currency formatting.

println(CurrencyFormatter.sharedInstance.stringFromNumber(20)!) //$20.00
println(CurrencyFormatter.sharedInstance.stringFromNumber(50)!) //$50.00

More to Learn

If you have found this information useful and would like to learn more, please sign up for the Swift newsletter below and I will send you updates when new posts and videos become available. You’ll also receive access to my video tutorial “Advanced Swift Arrays”.

Swift var vs. let – Screencast

My latest screencast is now available! This time I cover var vs. let in Swift. Topics I cover include:
– The difference between Var and Let
– Examples of variable values types like Strings and Ints
– How properties of reference types, like Classes, are affected
– I show an example using multiple classes and properties including inherited properties
– I demonstrate how properties of constant values types like Structs and Arrays cannot be change

This screencast is a part of a series I am doing on Swift development.

Introduction to Swift Arrays – Screencast

My first screencast on Swift development covers an introduction into Swift Arrays. This is the first screencast in a series I’m doing on Swift development. Here’s some topics that I cover in this video:
– How to create an array in Swift
– Declaration and Initialization of arrays in Swift
– Retrieving an item from an array
– Adding to a Swift array
– Iterating over the items in a Swift array

The topics in this video cover come from my post on arrays in “Swift for Rubyists”.

Swift for Rubyists: Dictionaries

This post is the second in a series I am doing on Swift for Rubyists.

Forgive me for the lines that wrap on this one. I did the best I could to try and format them on one line, but all of the examples from this post are available as a playground to download at this repo.

Update: Apparently, my changes to fix the “<” & “>” symbols missing in the examples didn’t save. Fixed now.

Swift Dictionaries

Swift Dictionaries are equal to Hashes in Ruby. Like Swift Arrays, Swift dictionaries are like dictionaries/hashes in most modern programming languages including Ruby. Although Ruby hashes and Swift dictionaries share many similarities, there are some areas where their behavior is very different.

Swift Dictionary Declaration and Instantiation

Declaring a Ruby Hash, like an array, is very simple.

{}

Just like arrays, there are three different ways to declare a Swift Dictionary. In the first two ways, you must declare the type of keys and values before you instantiate the dictionary:

var swift_dict: Dictionary
var swift_dict_again: [String: String]

It is important to note that when declaring a Swift Dictionary in these first two ways, you must declare a type for both the key and value. In Ruby, any object can be a Hash key, but you have probably most often seen them as symbols or strings like the following examples:

{:key => "door"}
{"key" => "door"}

In order to be used as keys for a Hash (make it “hashable”), Ruby requires objects to implement “#eql?” and “#hash” methods. Strings and symbols both do these by default in Ruby.

Swift dictionary key types are the same way. Swift requires dictionary types to implement the Hashable protocol, which requires two methods “#hashValue” and the “==” operator. Strings, Int, Bool are all hashable types by default in Swift.

So, if you ever felt adventurous, you could create your own Swift type that implements the Hashable protocol that you could use as a Swift dictionary key. That technique is beyond the scope of this post.

Swift Dictionary Literals

There are Swift Dictionary literals. A Swift dictionary literal is very similar to Ruby’s hash literal. You are probably pretty familiar with this as it is found all throughout Ruby web frameworks like Rails:

{:key => "value"}
//or
{key: "value"}

The syntax for a creating a Swift dictionary literal is slightly different, but very important. We lose the curly brackets and signature “fat arrow”, move the colon (depending on which Ruby syntax you choose) and add square brackets.

In Swift, curly brackets, {}, are very important. Swift uses curly brackets to define functions and closures. Swift uses square brackets for dictionaries. Here’s a Swift Dictionary literal:

var dictionary = ["key":"value"]

Like Swift array literals, we do not have to declare a type for the keys and values of the dictionary because Swift uses type inference to infer the kinds types for the keys and values. In this case, and

However, as I pointed out in my post on Swift Arrays for Rubyists, you must use literals in Swift carefully.

For example, let’s say you wanted to set the swift dictionary you created above to an empty dictionary. You would do the following:

var refrigerator = ["milk":"1%"]
refrigerator = [:]
println(refrigerator.isEmpty) //true

You might think that “[:]” is just the literal way of creating an empty dictionary. It is not. If you have imported Objective-C’s Foundation library, it will actually compile, but it creates an NSDictionary, not a Swift Dictionary. Here’s an example:

import Foundation

var not_a_swift_dict = [:]
print("\(_stdlib_getDemangledTypeName(not_a_swift_dict))")  //"NSDictionary"

If you want to create an empty Swift Dictionary, the proper way to do it is:

let swift_dic = [<SomeType>: <SomeType>]()

Remember from Swift arrays that declaring and instantiating a dictionary in Swift are two different processes. Unless you are using a literal, you have to declare a Swift dictionary and then instantiate it.

For example, if we declare a dictionary in Swift, but do not instantiate it, properties like “count” will not exist and will cause a compile error.

var not_instantiated_dictionary = [String: String]
not_instantiated_dictionary.count //error

Modifying a Dictionary

Obviously, hashes and dictionaries are not very useful if you can’t add/remove items to them. Luckily, Swift uses subscript syntax for adding new objects to a dictionary which is the same style of syntax as Ruby’s hash.

hash[<SomeObject>] = <SomeObject>

Here are two examples side-by-side both using Strings as the key and value type side-by-side:

ruby_refrigerator = {}
ruby_refrigerator["milk"] = "2%"

var swift_refrigerator = [String: String]()
swift_refrigerator["milk"] = "2%"

It is important to note that we are declaring the Swift dictionary as a variable. We haven’t covered the difference between constants and variables in Swift, but know that constants in Swift are immutable. In this case, that means we cannot add or remove items from them. So, we are declaring it as a variable.

You can use the Swift Dictionary method “#updateValue” instead of the subscript syntax. However, this method has an interesting side-effect. “#updateValue” will always return a Swift optional of the old value that it is updating.

We haven’t touched Optionals yet in Swift, but they are a big and complex part of Swift that we will go further in-depth on another blog post.

For now, the most important thing to remember about Swift Optionals is that they are a type that is either some value of that type or nil.

Why is this important to “#updateValue”? Well, let’s look at our milk example above. What if we substituted Swift’s subscript syntax for the updateValue method? Would it still work? Absolutely.

var swift_refrigerator = [String: String]()
swift_refrigerator.updateValue("1%", forKey: "milk") 

“#updateValue” will actually set a value for a key if no value exists. This is similar to Ruby Hash’s “#store” method.

However, “#store” and “#updateValue” return different values. Ruby’s “#store” will return the value that was just assigned. Swift’s “#updateValue” will return the original value for the key.

But what about our example? There was no original value for milk. So, shouldn’t “#updateValue” return nil? In many cases, Swift will return an Optional where nil is a possible return value.

In this case, Swift returns a String optional (written, String?). Here’s proof:

var swift_refrigerator2 = [String: String]()
let food = swift_refrigerator2.updateValue("2%", forKey: "milk")
print("\(_stdlib_getDemangledTypeName(food))") 
//Swift.Optional

We don’t have to specify that “food” is a String optional, because Swift is using type inference to decide the type of “food”. It already knows the return type of “#updateValue”, so we don’t have to specify it. Type inference is a powerful, but complex, feature of Swift that gives the compiled language a Ruby-like feel at times.

So, we could re-write our example above as:

var milk_optional : String? = swift_refrigerator2.updateValue("%2", forKey: "milk")

Removing a key and its value from a Swift Dictionary with “#removeValueForKey” returns a String optional as well and operates largely the same way.

var depleting_refrigerator = ["milk":"2%"]
let milkless = depleting_refrigerator.removeValueForKey("milk")
print("\(_stdlib_getDemangledTypeName(milkless))") 
//Swift.Optional

In the case that no key exists, Swift will still return an optional.

var eggless_refrigerator = ["milk":"2%"]
let hungry = eggless_refrigerator.removeValueForKey("eggs")
print("\(_stdlib_getDemangledTypeName(hungry))") 
//Swift.Optional

Iterating over a Swift Dictionary

Just like Ruby Arrays and Swift Arrays, Ruby Hashes and Swift Dictionaries are very similar in how you iterate over them.

Each data structure can use for..in loop for iteration. In Ruby:

best_pictures = {1973 => "The Godfather", 
                 1989 => "Rain Man", 
                 1995 => "Forrest Gump"}

for year, title in best_pictures
  puts "The award for Best Picture in #{year}: #{title}"
end
//Outputs
//The award for Best Picture in 1973: The Godfather
//The award for Best Picture in 1989: Rain Man
//The award for Best Picture in 1995: Forrest Gump

In Swift, while the syntax is similar, a Swift for..in loop over a dictionary returns a tuple, a Swift type that does not exist in Ruby. It essentially is a single type that can contain multiple types (a dream within a dream? I know. More on this later).

In this case, this allows the Swift for..in loop to behave very similarly to the Ruby for..in loop.

let best_pictures = [1973:"The Godfather", 
                     1989:"Rain Man", 
                     1995:"Forrest Gump"]

for (year, title) in best_pictures {
  println("The award for Best Picture in \(year): \(title)")
}

//Outputs
//The award for Best Picture in 1973: The Godfather
//The award for Best Picture in 1989: Rain Man
//The award for Best Picture in 1995: Forrest Gump

Swift .Keys and .Values

Just like Ruby, Swift provides a couple of convenient ways for getting only the keys and values of a dictionary.

In Ruby, “#keys” and “#values” are methods that both returns arrays of their respective items, like so:

roster = {:pitcher => "Justin Verlander", 
          :first_base => "Miguel Cabrera" }
positions = roster.keys //[:pitcher, :first_base]
players = roster.values //["Justin Verlander", "Miguel Cabrera"]

In Swift, they are slightly different. In Swift, .Keys and .Values are properties of a dictionary and return not arrays, but LazyBidirectionalCollections (isn’t that a mouthful)? To convert a LazyBidirectionalCollection into a Swift Array, you pass the collection into the Swift array initializer function. For example:

let roster = ["pitcher": "Justin Verlander", 
              "first base": "Miguel Cabrera"]
let positions = [String](roster.keys) 
//["pitcher","first base"]

Note: there is another, undocumented (at least by Apple), way to convert the .keys or .values collection into an array. Why this is not documented or discussed in any way is beyond me. See below.

You can also use the convenient “array” property on each of these collections to get an array of their respective values.

let roster2 = ["pitcher": "Justin Verlander", 
               "first_base": "Miguel Cabrera"]
let positions2 = roster.keys.array

More to Come

While we covered a bit about Swift Dictionaries for Rubyists, this post has only been a brief introduction. If you have found this information useful and would like to learn more, please sign up for my Swift Newsletter below and I will send you updates when new posts become available. You’ll also receive access to my video tutorial “Advanced Swift Arrays”.

Learn more about other areas of Swift from a Rubyist’s perspective.

Swift for Rubyists: Arrays

This post is the first in a series I am doing on Swift for Rubyists.

All of the examples from this post are available as a playground to download at this repo.

Update: I have corrected a mistake in this post which stated that mixed Swift arrays of Ints and Strings worked because they were inferred to be the AnyObject type. This was incorrect. This only works in cases where you have imported the “Foundation” library or if you use the type Any. My apologies. See this article for further explanation.

Arrays

Swift arrays are like arrays in most modern languages including Ruby. In some cases, they share some similar characteristics. In others, they are very different. We’ll compare how Swift handles arrays vs Ruby.

Swift Array Declaration and Instantiation

Due to type-safe nature of Swift, the declaration syntax of Swift arrays to Ruby arrays is similar, but the differences are very important.

Declarations

In Ruby, it couldn’t be simpler:

[]

In Swift, there are three main ways to declare an array. In the first two ways, you must declare the types that the array will hold. Here are the first two using an example of declaring an array to hold String types.

var swift_core: [String]
var swift_core_again: Array<String>

Literals

Luckily, Swift has a third option. They are literals and they are very similar to Ruby literals. The examples I use throughout this post will be mostly be literals. The syntax is almost identical.

ruby_array = ["Matz", "Patterson"]
var swift_array = ["Lattner", "Apple"]

In the case of literals, we do not have to declare a type for the array because Swift uses type inference to infer the type of objects that it can hold.

There is one important exception for using literals that I must point-out. It’s the shorthand syntax for how Ruby declares and instantiates an array. In Ruby, the shorthand way of doing this is:

arr = []

However, if you try to do this in Swift, and you have imported Objective-C’s Foundation library, it will compile, but it actually creates an NSArray, not a Swift Array. Take a look.

import Foundation

var arr = []
print("\(_stdlib_getDemangledTypeName(arr))")  //"NSArray"

So, if you try to use the Ruby shorthand for declaring and instantiating an array, you will get very different results in Swift.

If you wanted to do the above to create a Swift Array, you would use:

var arr = [String]()

Subtle, but important. There are actually ways to convert an NSArray to a Swift Array, but we won’t cover those in this post.

Let’s step back and talk about declaration vs. instantiation in Swift. Unless you are using a literal, Swift requires you to declare a type before instantiating an array. So, you actually have two steps if you decide not to use a literal. Declaring an array in Swift does not actually instantiate it. In this example, we declare a type in Swift, but do not instantiate it, so when we go to inspect the “count” property, we get an error.

var not_instantiated_array = [String]
not_instantiated_array.count //error

We haven’t actually instantiated our array so no “count” property exists. The proper syntax to do both is:

[<SomeType>]()

There are many reasons why you might want to declare an array, but not instantiate it, however, we won’t cover those here. Just know that Swift treats them separately when declaring an array.

Containing Items

Maybe the biggest and most important difference between Swift arrays and Ruby arrays is what kind of items that they hold.

In Ruby, arrays can hold multiple kinds of items in one array. For example, this is a valid array in Ruby:

mixed_array = ["apple", 1, OpenStruct]

On the other hand, Swift emphasizes type-safety. Swift arrays can only hold instances of one type.

Here are some examples of valid arrays in Swift:

var fun = ["Some Nights", "We Are Young", "Carry On"]

var lions = [9, 81, 90, 21]

var name = UILabel()
var email = UITextField()

var views: [UIView] = [name, email]

Mixed arrays, such as those of Ints and Strings, can be achieved only when you have imported the “Foundation” library. For example, here’s a valid array that holds both Int and String types.

import Foundation

var inebriated_array = [99, "bottles", "of beer"]

This can be achieved because Swift is automatically converting the instances to NSStrings and NSNumber classes. Check out this article here for more information.

Type-safety also applies if you try to add an element which does not match the type of the existing elements of an already instantiated array. For example, if we try to add an element using Swift’s “#append” method, this will not compile:

var broken_up = ["Blink"]
broken_up.append(182) //compile error

Appending

Ruby and Swift are almost identical with regards to the syntax of how to add an element on to the end of an array. Here’s an example in Ruby of adding two arrays together.

a = ["Simon"]
a += ["Garfunkel"]

In Swift, it’s the same.

var band = ["Simon"]
band += ["Garfunkel"]

In Ruby, you can use “#push”, which returns the modified array so you can assign it to something else.

chocolate_shake = ["Milk", "Ice cream", "Chocolate"]
mud_slide = chocolate_shake.push("Rum")

In Swift, you can use “#append”, but the method does not return the modified array.

var chocolate_shake = ["Milk", "Ice cream", "Chocolate"]
chocolate_shake.append("Rum")
print(chocolate_shake)

There is no equivalent to Ruby’s popular “<<” syntax out of the box. Although, we may cover this under Custom Operators later.

isEmpty vs. Empty?

Ruby provides many useful convenience methods for finding out more information about the state of an array. For example, Ruby provides an #empty? method to check whether an array has any elements.

vending_machine= []
vending_machine.empty? => true

Swift provides a similar feature via a property called isEmpty.

var vending_machine = Int
vending_machine.isEmpty //returns true

Iteration

Iterating over the elements in an array in Ruby or Swift are very similar. Like many languages, Ruby and Swift both offer a “for…in” loop. Here’s an example in Ruby.

beatles = ["John", "Paul", "George", "Ringo"]

for member in beatles 
  puts "Here's #{member}"
end

In Swift, the syntax is almost exactly the same.

var beatles = ["John", "Paul", "George", "Ringo"]

for member in beatles {
   println("Here's (member)")
}

If you need the current index of the element that you are iterating over, similar to Ruby’s “#each_with_index” method. You would use the “#emunerate” function in the for..in loop. Each iteration of enumerate returns a tuple containing the index and the element. We’ll cover tuples another time.

var beatles = ["John", "Paul", "George", "Ringo"]

for (index, member) in emunerate(beatles) {
  println("Playing #(index)")
  println("Here's (member)")
}

More to Learn

This is just a brief introduction to Swift arrays for Rubyists. If you have found this information useful and would like to learn more, please sign up for the Swift newsletter below and I will send you updates when new posts and videos become available. You’ll also receive access to my video tutorial “Advanced Swift Arrays”.

Learn more about other areas of Swift from a Rubyist’s perspective.

I also highly urge you to read Apple’s official documentation on Swift.

Introducing – Swift For Rubyists

As a Ruby developer, I had been looking to pick up iOS development for a while. I was lucky enough to take a course in it in the summer of 2014. The course covered Objective-C as well as the iOS API. Then Apple released the Swift programming language during the middle of the course, and the focus switched to learning Swift.

I’ve decided to write a series of posts on Swift for Rubyists. Theses posts will be centered around what I’ve picked up as a Rubyist learning Swift and the key points to note if you are a Rubyist who is attempting to learn Swift as well. I hope these posts will be helpful for other Rubyists looking to pick up Apple’s latest programming language.

Note: While Ruby is an excellent language, these posts are not meant to be a substitute for reading the Swift documentation and utilizing Swift’s own strengths and weaknesses. Using only the parts of Swift which are familiar to Ruby would be a waste of a very powerful and robust language. These posts are meant to be guides to help Rubyists transition to learning this fascinating new language.

Enjoy.

5 Vim Plugins that Helped Me Switch From Sublime

A month ago, I wrote a post about how I finally learned Vim. I gave a couple of simple steps that were the central focus of how I was able to switch from Sublime Text to Vim.

While these steps were the primary reason I was able to learn Vim, Vim plugins were a close second. While I had wanted to switch to Vim for a long time, I knew there would be parts of Sublime that I would miss. Little did I know the extensive power of vim plugins.

With a bit of browsing, Google-ing, and reading other developers’ dotfiles, I found a couple of plugins that would replace (at least, temporarily) certain functionality that was available in Sublime but was missing from Vim’s core. These plugins helped me slowly make the transition over to using Vim exclusively.

Here are the 5 plugins that helped me the most.

#1 Vundle

Vundle List of Vim Plugins

My Current List of Plugins

Similar to Sublime’s Package Control, the Vundle plugin is just a plugin manager (a dream within a dream?) Like many package managers today, it is inspired by Ruby’s Bundler, which is part of the reason I gravitated to it, because I’m already familiar with the Bundler model. After installing it, adding a new plugin to Vim becomes as simple as adding one line to your .vimrc file and running “:PluginInstall”

There are many plugin managers for Vim out there as well. Check out Pathogen if you would like an alternative.

#2 ctrlp

ctrlp vim plugin

Demo of ctrlp

One of my favorite parts of Sublime was the fuzzy file search capability that came out of the box. In Sublime, the command to open the search is “command+p” or “command+t”. I knew missing this finder would probably destroy me when switching to Vim. Luckily, there’s a Vim plugin which duplicates this functionality. The aptly named “ctrlp”.

Like all of Vim, the ctrlp plugin is highly customizable as well, which can allow you to change the plugin to your liking. For example, I changed the primary “ctrl+p” command to always flush the cache before opening the search so that it will index any new files that I’ve added. Also, you can configure it to ignore certain file types and directories (I’m looking at you ./tmp).

#3 NerdTree

nerdtree vim plugin

Ctrlp is great when you know the file(s) that you are looking for. But what if you don’t know the name of a file that you are looking for? In Sublime, you have the slide-out folder directory which will allow you to browse and navigate a project’s structure quickly.

NerdTree is a Vim plugin which will give you the same ability. Just a quick toggle (I’ve mapped it to Space + “ne”) and you can quickly open a “NerdTree” and navigate a project structure. Of course, you can do a lot more. This plugin is immensely useful when I can’t use ctrlp.

#4 tcomment_vim

tcomment vim plugin

I need to quickly iterate and try new ideas when I am developing. One of my tricks to do that is to comment out a line or block of code.

In Sublime, this is fairly straightforward. However, utilizing the excellent ‘tcomment’ plugin, commenting is even quicker. This plugin maps ‘gc’ to allow you to comment out large amounts of texts quickly. For example, if I want to comment out the next five lines of code, it’s simply ‘gc4j’. Like Sublime, it will also try to automatically recognize the language of the file and apply the proper commenting syntax.

#5 The Silver Searcher

the silver searcher

There were many times during my Sublime days when I would need to lookup and piece of code in a project. In Sublime, I would open up the project-wide ‘find-all/search-and-replace’ menu and type in what I was looking for. Sublime was usually quick to respond with where it could be found in the project.

Unfortunately, Vim does not come with current directory/project-wide search functionality out of the box, but luckily, there’s a great alternative.

The silver searcher is a *nix command line utility for replacing the search abilities of an ack or grep. And it is ridiculously fast.

Ok, I know what you are thinking…wait this is a command utility, not a Vim plugin. Correct. But, luckily some vim faithfuls have created a couple of Vim plugins which will allow you to use the silver searcher from a command in Vim. So, you can search can search an entire project without leaving Vim.

I use ag.vim. The experience is not as smooth as the command line and sometimes I have to jump out of Vim to use the full power of the silver searcher, but nonetheless, it gives me at least a close replacement to Sublime’s find-all.

Honorable Mentions

I have a few more plugins that I utilize in Vim. Some I use more than others. However, none were quite as important to my transition to Vim as the ones above.

The one exception is vim-rails, which is a MUST have Vim plugin if you are a Rails developer. However, I decided not to list it, because the rest of the plugins are language-agnostic and all developers seeking to make the transition can use them.

Here’s a few others that I use:

Vim Plugins…Good or Bad?

I’ve heard the argument that some feel that Vim plugins are too much of a crutch or that customizing Vim beyond recognition hampers your ability to pair with other programmers. These are all valid points. But the goal I had set for myself was to just switch to using Vim full-time for my development, so I wasn’t concerned with pairing or that I was using plugins as a crutch. I knew I had to learn to crawl before I could run.