A “What’s wrong with this Swift code?” problem

Published on: Oct 03, 2016

iOS Swift Swift Playground UIKit tips

Swift is a really great concise language. Together with Xcode Playgrounds, it makes for a great tool to use during interviews, both as an interviewee and as a candidate.

Here is a simple “what’s wrong with this Swift code” interview problem I stumbled across; it highlights a side effect of computed class variables:

swift

How to use it

Start with a playground with the code above (available as a gist here) and observe how the candidate’s approach to understanding why the label is not in white on a blue background like below.

swift

If stuck, ask why label.superview is nil after “being added as a subview”:

swift

Solution

Here is the solution:

swift

Hope you’ve found this useful.