Interesting Gotcha With UIButton Title

I was writing some code along these lines to set the background of a view based upon the value of the title of a button.1 Seems simple enough. The otherView.background should definitely be green at the end of this code. But it wasn’t. Can you figure out what I did wrong?

// starting condition - sender.titleLabel?.text == "invalidValue"

button.setTitle("validValue", for: .normal)

if sender.titleLabel?.text == "validValue" {
    otherView.backgroundColor = .green
} else {
    otherView.backgroundColor = .red

Turns out that setting the text of the titleLabel is an asynchronous, animated event. When we call setTitle(_, for:), we are setting the underlying title for a given state, and we also trigger an animated change to the visible titleLabel.text . So even if you call setNeedsDisplay or setNeedsLayout on the button prior to reading its value, titleLabel.text will not reflect the new value until the end of the animated change.

So, how do we get the correct value in an instant? Use button.title(for: .normal) 2 This reflects the “view model” value for the title in a given state, whereas the titleLabel.text value is what is actually displayed to the user at that instant.

  1. Actual example is more complex, but this gets to the heart of it. ↩︎
  2. replace .normal with a different state, if that is relevant ↩︎

4th spatial Dimension — Whoa!

NOTE: Not about coding today.

For no good reason, I started thinking about 4 dimensions. While I’ve seen a number of explanations of what a 4-dimensional object would look like from 3-dimensional space, I’ve never seen an explanation of what a 3-dimensional object would look like from 4-dimensional space. It occurred to me that in a universe with 4 spatial dimensions every point (inside and out) of a 3-dimensional object1 would visible to an observer. That is, every single point inside my 3D body would be perfectly visible viewed by an observer from 4 dimensional space.

Let me explain using an analogy to 2-dimensional space.2

First, look at the drawing below of a circle with dots on the inside, a triangle with lines inside, and the two-eyed observer. What can the observer see?

Since she’s two-eyed, she can perceive depth and therefore can see two distinct objects and can see that one is curved and can see that the other has one flat surface facing her, and that its surface is partially obscured by the object with the curved surface. But, she cannot see what is inside the objects, nor can she see behind the objects. But we, in 3-dimensional space can see the entire shape of each object, and we can also see literally every single point inside the entirety of each object, in a glance.

I understand this in the following way. In 2-dimensional space, observation is constrained by straight-lined trajectories within the x-y axes, but in 3-dimensional space, every point of a 2-dimensional object is viewable along an axis that is orthogonal to the x-y axes.

Now think of the analogous 3-dimensional objects. If I look at two people, one standing partially in front of the other, it’s just like the 2-d situation, I can see height, width, and depth of each object along a trajectory defined x-y-z axes, so I can’t the part of the person behind the other, and I can’t see the shape of the rear side of the people, and I definitely cannot see inside the people. But a 4 dimensional observer could see all of those things perfectly, in a glance along the orthogonal 4th axis. Whoa.

If it helps, you can make the further analogy of a 1-dimensional object being placed in 2-dimensional space: look at this picture, showing a straight line that merely varies in color along its one axis. The two dimensional observer can see the entire object, inside and out. There is no “behind” or “inside” for the 2-d observer.

I don’t have a “point” to this write-up, but I’ve always struggled to think of what higher dimensional spaces/shapes would look like, and this analysis doesn’t really answer that, but it does help me understand a little bit how our 3 dimensions might be perceived in 4-dimensional space.

  1. To be clear, in 4 dimensional space, it would actually be “a rendering of a 3 dimensional object”, just like a drawing on paper is a rendering of 2 dimensions, not actually 2 dimensions. ↩︎
  2. I’m just figuring this out on my own with inspiration from the idea of Flatland. I haven’t read it, and I am certain that others have fleshed these ideas out more fully and correctly elsewhere. But I haven’t personally come across this take before. ↩︎

UILabel + UISwitch Autolayout Bug?

I’m not sure that I have run into very many UIKit bugs in my career, but this sure seems like a bug to me. I have a UILabel and a UISwitch next to each other. Each is pinned with trailing & leading constraints as shown, but with no width constraints. The label has number of lines set to 0, and no other changes were made to compression priorities.

As you can see, no complaints from Interface Builder:

If I set the label’s text in ViewDidLoad to a string that is more than one line long, then I would expect that autolayout would see the switch and its required width, calculate the max width of the label based on that and the other horizontal constraints, and then set the label’s height accordingly. But the result that I get is as follows:

So the layout seems to be breaking the switch’s trailing constraint, however there are no error messages in the debugger.

If I switch the horizontal compression of the UISwitch to 751, then it lays out the views correctly:

The odd thing is that Autolayout is respecting the intrinsic size of the UISwitch, which can be verified by printing out the frame in the debugger after layout. So its not shrinking the horizontal size of the switch when it renders it. This means that it must be breaking the trailing constraint.

So the bug is two-fold. First, its calculating the width of the string based, perhaps, on a compressed UISwitch, but then laying out a UISwitch at full width, which necessarily breaking the trailing constraint of the UISwitch1. Second, it’s not providing any debugging information regarding the fact that it broke a constraint.

If I set the label’s text to the long version in Interface Builder, it recognizes the problem right away, as shown by the red lines, which further implies that there is a missing warning in the debugger:

  1. Right? Or maybe I’m missing something. ↩︎

That’s Weird!

While testing a particular part of a function in Swift, I added a return halfway through so that temporarily the rest of the code would not run. There were a number of things I was trying to avoid, but the first of them was a modal spinner dropping over the screen.

However, when I ran my code, the spinner was still dropping onto the screen. I was very confused and was searching all over the place for where else this modal may have been called from. Then I looked at the warning on the line invoking the modal:

I didn’t quite understand how the return could be given an argument in a Void function. I looked around for this error message and found this helpful blog post which reminded me that it is not the case that Void functions return nothing, but that they actually return a Void pointer/argument. And without a trailing semicolon at the end of the line containing the return, if the next thing after whitespace and newlines is of a Void type, then it will treat that as the argument to return.

Here is a quick demonstration of this:

  1. Warning with a Void function following return:
  1. Error with an Int returning function following return:
  1. Fix error with a semicolon after return:

That is logical, but crazy. At least the compiler will give you a warning (as long as your indentation is correct!). But I think that in a language that is trying to move away from pointers, it is pretty non-intuitive behavior, especially when it is so easy to treat a newline as though it were a semicolon.

I’ve added a comment to the effect to this issue at

Putting The Performance Lessons To Use

Putting The Performance Lessons To Use

tl;dr – working with primitives can be _waaay_ faster than objects.

I️ came across this tweet by Nick Lockwood, and the reply from Brian Gesiak regarding a string comparison method to find the “edit distance” between two strings. The repo can be found here

It’s a very cool algorithm, and the Brian explicitly stated that it was not written to be performant. While I am sure that there are number of algorithmic improvements that could be made in order to improve speed, that would also be difficult, and certainly more trouble than it would be to me, since I don’t really have a clue how this algorithm works nor do I have any need to use it right now. I’m not trying to brag about my ignorance, but it’s quite common that a programmer needs to balance effort vs. reward.

However, I did notice that the internal implementation uses NSString comparison methods. And as I learned recently, the first rule regarding performance is that objects are expensive and should be avoided when possible. So, it made curious how much performance improvement could be achieved by merely replacing the internal NSString implementation with an internal implementation using a primitive char array. Again, let me note that Brian explicitly stated he was not optimizing for speed, so this is in no sense a criticism of his code.

Other than dealing with the boilerplate of getting the array of bytes from the NSString, the only change that needed to be made to the code was one line of code for comparing whether a letter at an index.

if (![NSString mdc_sameCharacterAtLeft:left index:y-1 right:right index:x-1]) { substitution++;}vs.
if (lBytes[y-1] - rBytes[x-1]) { substitution++;}This is the implementation of the comparison method in the example (mdc_sameCharacterAtLeft) code:
return [@([left characterAtIndex:leftIndex]) compare:@([right characterAtIndex:rightIndex])] == NSOrderedSame;This line of code is actually carries a lot of object-based overhead, including:
  • 2 characterAtIndex method calls
  • 2 primitive -> object instantiations (@(value))
  • and finally one more compare: method call

I think we can agree that this will be a bit slower than the subtraction of two ints.

Using “sitting” and “kitten”, we get:

Average runtime (koyachi): 14640 s, distance: 3Average runtime (Gesiak ): 11261 s, distance: 3Average runtime (Bytes ): 3562 ns, distance: 3So, the difference I found between Koyachi implementation and Brian's implementation is similar to what was reported, i.e. ~30% faster. However, the Bytes implementation gives a 3x speedup (i.e. 300% faster) over Brian's implementation.

Using the strings defined for comparison in the Github repo on an iPhone 7 with -O3 optimization we get the following results:

Average runtime (koyachi): 0.062313 s, distance: 463Average runtime (Gesiak ): 0.052492 s, distance: 463Average runtime (Bytes ): 0.001969 s, distance: 465You'll notice two things. First of all, to the main point of my exercise, we see a 27x speed up, which is a fairly typical result after multiple runs. That is a big gain. looking at the raw times, if this were UI critical work I️t would be the difference between something that could be done easily within a frame rate refresh and something that would lead to significant frame droppage.

But, we also see that the distance is incorrect. The second string contains this name, “Damerau–Levenshtein”, which included a non-ASCII dash character, something I never would have noticed. When this is replaced with an ASCII dash, the distances all match. However, this clearly demonstrates the tradeoffs between using primitive values vs objects.

If one really wanted to use this approach then the strings could likely be tested for ASCII compliance with something like, [string smallestEncoding] and one could be clever about which method to use, and likely implement primitive methods dedicated to many common so that the fastest methods could be used most of the time (NSString is a class cluster for a reason!). Also, unichar/unicode rather than Byte primitives could also possibly be used, but that would depend on one’s needs and I am not expert enough to comment on that.

modified code:

Oh, That’s What NSAssert1 Is For!

<smacks forehead>

In the instances, where I have used NSAssert, I have noticed autocompletion suggesting the existence of NSAssert1, NSAssert2, NSAssert3, NSAssert4, NSAssert5, and I proceeded to ignore them every time.

Today, I finally figured it out because I wanted my Assertion message to contain the value of the parameter that is failing, and NSAssert doesn’t work with NSString stringWithFormat:

NSAssert(condition, @"msg to future");
NSAssert1(condition, @"msg to future with parameter: %zd", intParam);
NSAssert2(condition, @"msg to future describing parameters: %zd %zd", intParam, intParam2);

Notice a pattern?

NSAssert is just a macro, and clearly it was not implemented for variadic arguments. The 1, 2, 3… not elegant, but it is quite clear how to use it correctly, which is very important for functions used when asserting. So maybe the lack of a variadic option is not an accident.

Bonus points: NSCAssert(n) is for Asserts inside of C function.

The Term `guard` Is Confusing

Swift introduced the following construct::

guard  else {
//perform desired code

As an alternative to:

if condition {
    //perform desired code

It provides a mechanism to encourage a clearly delineated grammar for early returns or fatal errors if a condition is not met. It is an elegant syntax for two reasons:

  1. It makes the intention clearer than just an if statement by letting subsequent readers know that there are particular conditions that should be met before running the code.
  2. It allows for less nesting, particularly when there are multiple, co-dependent conditions, so you can avoid “pyramids of death”. i.e.:
if condition1 {
    if let param = optionalParameter {
        //transformation needed to evaluate cond3
        if condition3 {
            //perform desired code
            //use param 


guard condition1, param = optionalParameter else {
//transformation needed to evaluate condition3
guard condition3 else {
//perform desired code
//use param

So, I really love guard statements, but for a long time, I struggled to remember if I would want a particular condition to be true or false. I basically couldn’t remember if guard meant “guard against this condition” or “guard the code from this condition being false”.

So, I eventually figured out that I could remember what I wanted the guard condition to be if I said in my head “Make sure this condition is true, otherwise…”. i.e.:

makeSure condition else {

So, for a while, I was happy to just say to myself “make sure” every time I wrote a guard statement, but I recently thought it would be nice if the language itself made this clearer, and sure enough I just found a Swift evolution pitch proposing exactly that, using the word ensure, but it was rejected for a few (dumb!) reasons, and is unlikely to be revisited. However, I still wish it hadn’t been rejected, or that it were easier to alias the syntax.

Anyway, in honor of Jay Abbott, the author of the above pitch, and in honor of his profound wisdom, insight and common sense, I wrote this little gist for cases where the guard is only merely a boolean:

func ensure(_ arg: Bool, otherwise: (() -> ())) {
    guard arg else {

ensure(str2 == str, otherwise: {

Jay, your pitch will not be forgotten!