Swift 2.1 Function Types Conversion: Covariance and Contravariance

Published on September 29, 2015

This Swift 2.1 post requires Xcode7.1 beta or later, get this and other playgrounds from GitHub.

In Swift 2.1, coming with XCode 7.1 (see release notes), function types will support covariance and contravariance, let's see why this will matter.

In the context of computer science and types, the term variance refers to how the relationship between two types influences the relationship between the complex types that have been derived from them. This relationship between complex types is the result of either invariance, covariance and contravariance applied to the original types. Understanding how this derived relationship is defined is essential to effectively use complex types.

To clarify this, using pseudocode, let's consider a complex parametric type List<T> and two other simple types: Car and Maserati, a subtype of Car.

Invariance, Covariance and contravariance can be explained as follow considering the relationship that could bind the two types obtained choosing a specific T for List:

  • Covariance: If List<Maserati> is also a subtype of List<Car>, then the type relationship between the original types is preserved on List because List is covariant on his original type.

  • Contravariance: If instead, List<Car> is a subtype of List<Maserati>, then the type relationship between the original types is reversed on List because List is contravariant on his original type.

  • Invariance: List<Car> is not subtype of List<Maserati> and neither the opposite, the two complex types have no derived relationship.

Each language employs a specific set of variance approaches, knowing how complex types are related to each other helps understanding if two complex types are compatible and could be use interchangeably in some situations, in the same way a type and its subtypes do.

In the context of function types, complex type compatibility boils down to one simple question, when it's safe to use an alternative function of a type B where a function of type A was expected?

The general rule is that a compatible function type can have more generic parent types for parameters (the client of A function will be able to manage a more specialized parameter than what A declared) and can return as result a more specific subtype (the clients of the A function will treat the result as the simpler parent type declared in A). Contravariance applied to parameters and Covariance to what is returned.

Before Swift 2.1, function types behaved in an invariant way, if you try to run the code below in a playground, you will get a few variations of this error: Cannot convert value of type '(Int)->Int' to expected argument type '(Int) -> Any'.

func testVariance(foo:(Int)->Any){foo(1)}

func innerAnyInt(p1:Any) -> Int{ return 1 }
func innerAnyAny(p1:Any) -> Any{ return 1 }
func innerIntInt(p1:Int) -> Int{ return 1 }
func innerIntAny(p1:Int) -> Any{ return 1 }


With Swift 2.1, this changes, function type conversion is supported and function types are now contravariant regarding parameter types and covariant regarding the result type.

Back to the code sample, is now legal to pass all the three Any->Any, Any->Int, Int->Int functions to the testVariance function with a Int->Any parameter of the example above.

A Brief iOS9 UIStackView Guide

Published on September 8, 2015

This Swift 2.0 Guide requires Xcode7 beta or later, get the complete project from GitHub or zipped.

iOS9 introduces UIStackViews, a new component that greatly simplifies building layouts that can be broken down to vertical or horizontal sequences of UIViews, providing an alternative to manually positioning views using auto-layout.

Acting as an invisible container, each UIStackView is able to display a single sequence of subviews (arranged views) aligned either vertically or horizontally, automatically resizing its content according to the current screen size and adapting to changes in orientation. How these subviews are actually positioned depends on a few properties that define how the subviews should be aligned, spaced and, if needed, resized.

What happens under the hood is that the UIStackView class manages auto-layout constraints for you. Think of UIStackView as an abstraction layer above auto-layout that simplifies the creation of a well defined subset of layouts. You can start building your layout from a main UIStackView and add nested UIStackView until all your UIViews are positioned correctly.

If you have done any Android development, you'll notice that the UIStackView concept is quite similar to LinearLayouts, likely the most used android layout scheme, that in turn borrowed some ideas and improved upon the multitude of layouts that were already available in Java Swing.

The Basics

As usual, UIStackViews can be created both programmatically and in Interface Builder.

In Interface Builder you can add a new vertically or horizontally aligned UIStackView choosing the right control from the Object Library and once the view is in place, new views can be added dragging controls inside the UIStackView.

A new UIStackView can also be wrapped around one of more existing views, just select them and click the new Stack icon you'll find in the bottom bar of Interface Builder.

Quite simple, but in this guide we'll create a basic nested layout programmatically.

UIStackView example

In this brief example, a vertical UIStackView, placed right below the status bar, will contain four controls: two UILabels, one horizontal UIStackView and one UIButton. Three buttons with default icons will be placed inside an inner horizontal UIStackView.

Let's start, create a new Single View Application, verifying that the selected Deployment Target is 9.0+.

Open your only ViewController and replace the viewDidLoad method with this one:

    var stackView:UIStackView!
    var nestedStackView=UIStackView()

    override func viewDidLoad() {

        // Main UIStackView contraints, nearly fills its parent view
            options: NSLayoutFormatOptions.AlignAllLeading,metrics: nil, views: ["stackView":stackView]))
            options: NSLayoutFormatOptions.AlignAllLeading,metrics: nil, views: ["stackView":stackView]))

        stackView.axis = .Vertical
        stackView.alignment = .Fill
        stackView.spacing = 25
        stackView.distribution = .FillEqually
        var lbl = UILabel()
        lbl.text="Label 1"
        lbl.backgroundColor = UIColor.redColor()
        lbl = UILabel()
        lbl.text="Label 2"
        lbl.backgroundColor = UIColor.greenColor()

        nestedStackView.axis = .Horizontal
        nestedStackView.alignment = .Fill
        nestedStackView.spacing = 25
        nestedStackView.distribution = .FillEqually
        nestedStackView.addArrangedSubview(UIButton(type: .InfoDark))
        nestedStackView.addArrangedSubview(UIButton(type: .InfoLight))
        nestedStackView.addArrangedSubview(UIButton(type: .ContactAdd))
        let btn=UIButton(type: .System)
        btn.setTitle("Press Me", forState: .Normal)

To specify a vertical orientation for the main UISTackView we are setting the axis property to .Vertical, the first three controls will be equally spaced and the UIButton will fill the rest of the available space. The three buttons with default styles contained in the inner nestedStackView will be arranged in a similar fashion. The alignment, distribution and spacing properties will be explained in the next section, ignore them for now.

Sooner or later you will need to hide and show some of the arranged views and this is quite straightforward for UIStackViews, just set the hidden property of one of your views.

To test this, let's add an action to the UIButton and a new pressedMe method as follow:

        btn.setTitle("Press Me", forState: .Normal)
        btn.addTarget(self, action: "pressedMe:", forControlEvents: UIControlEvents.TouchUpInside)
    func pressedMe(sender: UIButton!){
        UIView.animateWithDuration(0.5) {
            self.nestedStackView.hidden = !self.nestedStackView.hidden

Clicking the button will now hide or show with a short animation the inner UIStackView and the main UIStackView will reposition the remaining views according to the properties specified in viewDidLoad.

If needed, subviews can also be completely removed from the UIStackView and all the contained arranged views will be, again, repositioned according to the current properties.

    func pressedMe(sender: UIButton!){

Removal is a two step process, calling the removeArrangedSubview method will remove the view from the UIStackView and reposition the remaining subviews but will not remove the view from its superview. The removed views need to be completely removed from their super views too, or they will still be shown outside the UIStackView. To do this, simply invoke removeFromSuperview on the removed view.

UIStackView: Alignment, Distribution And Spacing

Let's take a look at the positioning properties UIStackView exposes:

UIStackView properties


Defines along which axis your views will be positioned, has two possible values: Vertical, Horizontal.


The alignment property specifies the perpendicular (to the selected axis) alignment for your views, the value Fill will also resize all your views to fill the available space, the other values will not modify your views size. Available values are: Fill, Leading, Top, FirstBaseline, Center, Trailing, Bottom, LastBaseline.


Distribution specifies how the subviews should be resized or distributed to fill all the available space along the axis, the possible values can be divided in two groups: fill and spacing values.

Fill values modify the size of the subviews if they don't fill (or fit in) all the available space. The spacing between the subviews will be the one specified with the spacing property.

  • Fill: The subviews will be shrinked or stretched according to their content content resistance or hugging priority. If you didn't set any, one of the subviews will be modified to fill the space available.
  • FillEqually: Disregarding any constraint, the subviews will be resized to the same size along the axis.
  • FillProportionally: The subviews will be proportionally resized according to the original size of each subview.

Spacing values fill the space along the axis altering the spacing between the subviews, the size of the subviews will be modified, according to the compression resistance, only if the subviews still don't fit or if any auto-layout ambiguity arises.

  • EqualSpacing: The subviews will be equally spaced
  • EqualCentering: The subviews center axis will be equally spaced


The spacing property is expressed in points and its meaning depends on the current distribution value.

If the UIStackView distribution property is either EqualSpacing or EqualCentering, the spacing property will represent the minimum spacing among subviews. Alternatively, if a FillProportionally distribution was selected, the requested spacing value will be exactly the chosen value.

UIStackViews: iOS7+ Backports

UIStackViews are supported only from iOS9 onward but a few backports, that partially implements this feature in iOS7 or later, have already been built:

From VIM Theme to Pygments CSS

Published on September 21, 2011

I have just converted a few VIM themes to CSS that can be used with Pygments using the python script described here (GitHub repo).

If anyone is interested (you'll need this if you are using Jekyll), the GitHub repository with the CSS files can be found here and at the moment it contains the following VIM themes: desert, mustang, no_quarter, peaksea, railscasts, rdark, slate, wombat, nuvola.

Feel free to fork the repository and add your own converted themes, an example of the result using the github theme can be seen below, enjoy!

public static class IntTimes
              implements ScalaObject

    public void times(Function1 what)
    private final int n;

    public IntTimes(int n)
        this.n = n;

First steps in Scala: Implementing Ruby's Integer.times

Published on September 21, 2011

After reading Seven Languages in Seven Weeks:A Pragmatic Guide to Learning Programming Languages i was left with the desire to know more about a couple of languages, namely Scala and Clojure. While i had some experiences with functional programming (Standard ML, Scheme) and other programming paradigms (Prolog) during the university, now some years have passed.

I strongly suggest you to buy the book even if you already know some of the described languages (Ruby, Io, Prolog, Scala, Erlang, Clojure, Haskell), it only gives a gist of these seven languages in a set of lessons ideally completed in three days (that with some individual unguided experimentation will fill a full week) but with its style will make you hungry for more.

If you need a suggestion on a Scala book, at the moment i'm going through Odersky's Programming in Scala and up until now it seems a good book even for those without prior experience in functional(ish) languages. Also, unlike other books, the first chapters are free of enigmatic examples that will only confuse beginners.

I'm practicing Scala solving some problems at Project Euler and for one of those i decided to implement something that resembled Ruby's .times and check the produced java bytecode to get a glimpse of scala's inner workings.

object scalatimes extends App{
  implicit def int2inttimes(n:Int)=new IntTimes(n)
  class IntTimes(n:Int){    
       def times(what:Int=>Unit){
           (1 to n).foreach(what);

  1000.times { n =>
      val n2=n+1;


The implementation of times is quite trivial, this code makes use of implicit conversions to add to the Int type the new method through the implicit conversion of Int objects to the new IntTimes in the scope of the scalatimes object.

The times function simply uses the given function object of type Int=>Unit within a foreach cycle, the current index will be accessible inside the function body (i suppose that there are better ways to do this). But what kind of java code does the scala compiler produces for this example? A quick check shows that six class files are built:

  • scalatimes
  • scalatimes$
  • scalatimes$$anonfun$1
  • scalatimes$delayedInit$body
  • scalatimes$Int2
  • scalatimes$IntTimes

These files follow the usual java .class naming conventions,so the scala compiler produces a scalatimes class with a few inner classes. The class files can be decompiled with Jad but the decompiled result will be only partially complete. But anyway, this will help to understand what is happeing behind the scene. As expected, the body of IntTimes is contained in an inner class with the same name:

public static class IntTimes
              implements ScalaObject

    public void times(Function1 what)

    private final int n;

    public IntTimes(int n)
        this.n = n;

The times method expects a Function1 object as parameter, the body of the function passed to 1000.times() as parameter has been wrapped in an anonymous inner class (as per Jad comment):

/* anonymous class */ 

public static final class anonfun.cls1 
                    extends scala.runtime.AbstractFunction1.mcVI.sp
                    implements Serializable

    public final void apply(int n)

    public void apply$mcVI$sp(int v1)
        int n2 = v1 + 1;

    public final volatile Object apply(Object v1)
        return BoxedUnit.UNIT;

    public static final long serialVersionUID;

        serialVersionUID = 0L;


The two lines of code that compose the function object body passed to 1000.times() are clearly visible in apply$mcVI$sp(int v1). The main method of the App can be identified in the body of the apply() method of a static class that extends AbstractFunction0:

public static final class on0 extends AbstractFunction0
                    implements ScalaObject{

    public final Object apply()
        $outer.int2inttimes(1000).outer(new ());
        Predef$.MODULE$.println((new StringBuilder())
                        .append(BoxesRunTime.boxToLong(System.currentTimeMillis() - $outer.t1()))
        return BoxedUnit.UNIT;

    private final scalatimes$ $outer;

    public on1.mcVI.sp(scalatimes$ $outer)
        if($outer == null){
            throw new NullPointerException();
        } else {
            this.$outer = $outer;

Function0, like the Fuction1 above, is a scala framework object, likely related to the class extended above, and some helper methods in scalatimes hints to the fact that it will be loaded using a delayedInit() call (by an App loader?). And this ends for now my brief and superficial investigation on the structure of the code produced by the Scala compiler.

This is the blog of Umberto Raimondi, you can reach me at me@this domain.

Get the RSS feed. I'm also on GitHub and Twitter.