There’s a subtle API design issue that’s helpful to be aware of here...
as they explain, if you insertSegment beyond the number of segments in topCaptionSegmentedControl, it is simply added as the last segment: First segment 0, then segment 1, etc…
UISegmentedControl is a little unusual among array-like data structures as it happily accepts an out-of-bounds index. You could even do this:
topCaptionSegmentedControl.insertSegment(withTitle: choice.emoji, at: 9999999, animated: false)
In fact most of the segmented control methods that accept an index are documented that way:
An index number identifying a segment in the control. It must be a number between 0 and the number of segments (numberOfSegments) minus 1; the segmented control pins values exceeding this upper range to the last segment.
But data structures like NSMutableArray or Swift Array will fail if you pass an out-of-bounds index like that.
IMHO, this was a poor choice in the UISegmentedControl API design. It’s trying to be helpfully forgiving, but this can just mask bugs in the calling code, and is inconsistent with other array-like APIs you use every day. It’s even internally inconsistent: it helpfully clamps indexes that exceed the upper bound, but not the lower bound. Passing +999 works but -1 fails.