Mind-Blown By Swift's Type System
Swift's type system is a source of frustration and not few developer state that it solves a problem nobody had. In my opinion it's useful mainly for beginners. It helps to find misunderstandings of Cocoa APIs and other people's code early. But I also think that the influence on the number of bad bugs in shipped apps is low. Most of the prevented errors are so obvious that they get caught during debug runs.
But a few days ago I stubbled across a feature of Swift's type system that blew my mind.
You sure have seen already this kind of type inference:
func aNumber() -> Int { return 1 }
func aNumber() -> Double { return 2.0 }
let a: Int = aNumber() // -> 1
let b: Double = aNumber() // -> 2
The constant a is declared to be of type Int and therefore the first version of aNumber() is called. In the case of a Double on the left side of the assignment (b) the second version is called.
So far so good. Let's take this to the next level. UIView has an initializer that takes a CGRect. This makes the following type inference possible:
var coloredView = UIView(frame: .zeroRect)
So the compiler already knows that the frame only can be a CGRect and accesses the corresponding property zeroRect of CGRect.
This is already kind of cool. But there is more. The type system can handle code like this:
coloredView.backgroundColor = .yellowColor()
And this blew my mind. It make the code easier to read an removes unnecessary cruft. But it's also kind of obvious because it's kind of the same as the previous example in the initializer of UIView.
And then I became high-spirited and tried this:
var layoutConstraints = [NSLayoutConstraint]()
layoutConstraints += .constraintsWithVisualFormat("|-[stackView]-|", options: [], metrics: nil, views: views)
(Note that NSLayoutConstraint is missing in front of constraintsWithVisualFormat(...).)
Unfortunately it doesn't work. To find out what the problem is I changed the code to:
let theConstraints: [NSLayoutConstraint] = .constraintsWithVisualFormat("|-[stackView]-|", options: [], metrics: nil, views: views)
and got the error:
'[NSLayoutConstraint].Type' does not have a member named 'constraintsWithVisualFormat'
This means the compiler uses the type on the left side to find a method with the signature from the right side of the assignment. This obviously doesn't work and I'm not sure if it should work. It would make my code more compact but at some point more compact becomes to compact.
If you enjoyed this post, then make sure you subscribe to my feed.