Archive for the ‘Development’ Category

SwiftUI: Modal presentation

I have regrettably little time to devote to SwiftUI. I explore when I can, although I wish I were a lot further in that journey.

Here’s my latest go, where I’m looking to build a modal presentation. Today is the first time I’ve been able to play with Modal, the storage type for a modal presentation. I tied it together with an isPresented state, but I’m wondering if I’ve done this all wrong.

I can’t help but think there’s a better way to do this. I’m using a text button for “Done” instead of a system-supplied item, so it won’t be automatically internationalized. Nor, can I find any specialty “Done” item in SFSymbols. When looking at Apple’s samples, such as Working with UI Controls, I see the same Text("Done") . While I know that Text elements are automatically localized should resources be available, is SwiftUI providing us with any core dictionary of terms?

I think using the isPresented state in the code below may be too clunky. I’d think that there would be a more direct way to coordinate a modal item. Any advice and guidance will be greatly welcomed.

I remain stuck in Mojave for most of my work, although I put an install of Catalina on a laptop. Although you can build proper SwiftUI apps using the beta Xcode, without the preview (and I’ve had no luck finding a secret default to enable it under Mojave) makes the experience way slower than working in a playground.

I’m hoping to dive next into Interfacing with UIKit.

SwiftUI: Boing!

Source: here

Note that you add the animation to the View object and update the view’s state in the gesture state handlers. The onEnded action passes a summary of the velocity, offset, and location of the gesture but I ignored it because I didn’t need it.

SwiftUI: Embracing the nonobvious?

This is going to be another day where I get to play with SwiftUI because I can’t get any real work done right now and am dealing with lots of interruptions.

This morning, I returned to yesterday’s mouse inventory sample to try to get my rounded corners working. Several people suggested that I implement my interface using a ZStack and a Rectangle, so I tried that first.

To my surprise, the Rectangle expanded my VStack and I haven’t to date figured out how to constrain its size to be no more than its sibling. I wanted the rectangle to grow weakly instead of pushing the title and total items towards the edge of the parent view, the way it did in this screenshot:

Here’s what it looks like without the monster-sized Rectangle, which I think is a much more appealing layout:

So instead, after messing around a bit, it occurred to me that everything is a view or at least everything is kind of view-ish and if so, then I could possibly apply my corner rounding to Color, which I did.


And surprise, this is what I got:

Isn’t that cool?

Although the final layout is exactly what I wanted, if you think about it, it’s not that intuitive that system uses tight placement for this and lax spacing for the one with the Rectangle.

In fact, as a developer, I’m not happy about not having direct control over the tightness of either layout or an obvious way to relate ZStack siblings. If there’s a way to describe how much content hugging I want in a ZStack layout and how to prioritize which item in that layout should guide the others, I haven’t discovered it. If you have, please let me know!

I’m still trying to learn to best use the deeply mysterious Length (and, no, don’t tell me “it’s just CGFloat“, because clearly it isn’t “just” that with all the Angle, Anchor, GeometryProxy, UnitPoint stuff,  and so forth) and apply layout relationships. Today, time allowing, I’d certainly like to learn more about the mysterious TupleView, a View created from a swift tuple of View values and see where it is used, the ForEach, which computes views on demand, Groups, EquatableView, and so forth.

SwiftUI: A little state

I wish I had more time to play. Here’s a little SwiftUI thing I threw together in the few moments I had free today. The source code is here.

Interestingly not including Color for backgrounds seems to kill my poor little sample. I suspect an overload where the type cannot be unambiguously inferred. Adding corner radiuses (shown here on the outside) destroys user interactivity. I have it commented out in the gist.

Originally, I tried to control state extrema (no negative inventory) in my model object but that led to a disconnect with the steppers. Instead, I finally found an initializer that allowed me to specify the valid range (in: range) to sanitize the user input, and disable the minus button for zero values.

A lot of the time I spent putting this together ended up with “helpful” results that looked like this:

That is to say, it’s really hard to provide a fluent functional framework in a typesafe language that feels like you’re constructing things into type erased collections because you never actually are…if that makes sense.

So far this week, I’ve managed to watch one video (the keynote) and about 20 minutes of another (the first bits introducing SwiftUI). I hope I have a chance to catch up. I’ll try to keep notes here on the website as I work through some of this stuff. It feels weird this year how far behind I am due to work commitments.

I spent today out of the office due to personal commitments and it’s been the first time I could really dive in (well, “dive” meaning for 10-20 minutes at a time here and there during the day). Loving this stuff, can’t wait to do more.

Good Things: SwiftUI on Mojave in iOS Playgrounds

Yes, you can upgrade to the Catalina Beta. Or, you can keep getting work done on Mojave and still enjoy the glory of SwiftUI exploration.

  1. Install Xcode 11 beta along side your 10.2.x Xcode
  2. Using the beta, create an iOS playground. (This won’t work with macOS, which attempts to use the native frameworks, which don’t  yet support SwiftUI)
  3. Import both SwiftUI and PlaygroundSupport.
  4. Set the live view to a UIHostingController instance whose rootView conforms to View.

Here’s an outline of the basic “Hello World” setup:

From there, you can create pages for each of your SwiftUI experiments, allowing you to build short, targeted applets to expand your exploration and understanding of the new technology.

Bad things: Extension Access Control

Swift extends the courtesy of an access control annotated extension to its top level members. I’m going to call this “inheritance”, but I know there’s a better name for this but I just don’t know what it is.

Consider the following:

// Base type is public
public struct MyStruct {}

// Here, the extension is declared public, so each top level member
// "inherits" that access level.
public extension MyStruct {
  // This is public even if it is not annotated
  static var firstValue: String { return "public" }

  // This is also public but the compiler will warn.
  public static var secondValue: String { return "public but warned" }

  // This class is also public via "inheritance" 
  class PublicSubclass {
    // However, its members must be annotated. This is public
    public static let publicValue = "public"
    // This defaults to internal
    static let internalValue = "internal"

In this example, firstValue inherits the public access level from the MyStruct extension. The explicit annotation for secondValue is warned by the compiler as unnecessary.  If you treat warnings as errors, that’s a problem.

Each of the static properties are accessible outside the module except for internalValue, as even in a public class declaration, its members do not inherit its control level:

Before I start putting some preliminary style guidance out there, I’d like to point out a few more things about this. Here’s a second example:

internal class InternalType {}

extension InternalType {
  public static var value: String { return "value" }

Swift compiles this code without error. It is clearly a developer-sourced issue. The intent to make the member public is fundamentally flawed. as it exceeds the type’s access control level. This issue also exists outside of extensions, where the compiler will not warn on too-high levels for direct type members:

internal class AnotherInternalType {
  public var value = "value" // no warning

You’d imagine this is a place where the compiler should up its game, no? This is a point of code that is technically functional and compilable but whose specification undercuts the documenting nature of using access control. Shouldn’t the annotation be limited and warned here?

The compiler will find mismatches between the extension ACL and the type ACL:

And that’s where the problem comes in because the guidance I’m working on says: “Do not annotate extensions with access control levels except when working with trivial utilities”. Skipping extension ACL ensures that you can meaningfully and intentionally add access control to each member declared within that extension. Each access level is co-located with the declaration it decorates. This makes your code more easily audited and its access levels will be immediately apparent as to intent and implementation.

What are your thoughts? Can you think of any reasons why extensions should ever be ACL’ed in production code? And is this just a bug/language enhancement thing or is there something I’m missing. Thanks in advance for your feedback.

Teaching collections: shifting paradigms and breaking rules

Just because some things look alike and may act alike at some level, doesn’t mean that they should be taught at the same time, under a unified umbrella of learning. Consider bagels and donuts. They are both toroids . You can layer several instances onto a stick for storage or serving. You can cut them both in half. If you have no taste or sanity, you can place custard — or, cream cheese, salmon, onions, and capers — interchangeably between the two sides of either item.

Despite these common API surfaces, their use-cases, edge conditions, and recipes share little overlap. Conformance to ToroidFoodstuff does not correlate with each preparation of dough, the cooking process, or the serving and accoutrements associated with either food.

So why do we always have to lump arrays, sets, and dictionaries into a single lesson on collections?

A new language learner has little interest in traversing dictionaries, although it’s possible, or taking a set’s prefix, which is also allowed. Nor are new learners always prepared to take on optionals, the core return value for dictionary lookups, early in the language learning process.

I’ve recently spent some time helping to outline an introductory sequence for Swift learning. I pitched eliminating collections as a single topic unto itself. I want to reject superficial similarity and build language skills by introducing simple, achievable tasks that provide measurable and important wins early in the learning process.

Take arrays. They can store numbers and strings and more. You can grow them, shrink them, slice them. They have a count. They have indexes.  Arrays are perfectly matched with iteration in general and for-in loops in particular. Arrays and for-in iteration work hand-in-hand. So why not learn them together?

The answer is generally that arrays belong with collections and for loops belongs within a larger set of iteration topics. Ask yourself whether new coders actually need while and repeat-while loops in their initial approach to the language? How often in normal Swift coding do you reach for those two for simple reasons in simple code?

I’m not saying while-loops shouldn’t be taught. I’m trying to figure out what sequence of incremental learning provides new Swift developers with the most coherent set of basic tools they need to express themselves and expand their understanding over time.

Every classroom minute spent mastering while is a minute that could expand and practice for. Introductory lessons should focus on the core terms and patterns most commonly used in the workplace. Expressive language vocabulary can always be expanded through practice and engagement. Classroom minutes represent the restricted path.

Dictionaries, I argue, should be taught late. Every lookup is tied directly to optionals, a dictionary’s native return type. And optionals are quite a conceptually heavy topic. Dictionaries are the perfect pairing.  The type is a natural source of optional output, and an opportunity to discuss nil-coalescing and default fallbacks.

From there, you can pull in failable initializers, and optional chaining.  Dictionaries also lend themselves to advanced concepts like (key, value)-based for-in loop tuples, the key-value basics of Codable, and how custom structs relate to key-value coding, not to mention the entire conversation about nil, errors, try?, and more.

As for sets, well, I love sets and use sets, but are sets even appropriate for new learners outside of some sense of “completionism” learning? Should they be taught only because they’re one of the “big three” collection types? I’d argue that people should learn sets when they are already proficient in core language basics, not in the most introductory setting.

For example, you can tie sets into a lesson on view touches. Just because they’re a collection doesn’t mean that the newest students have to learn every collection right away, just as they don’t need to learn NSDictionary, NSArray, and AnyObject, and so forth, in the first days or weeks of exposure to Swift.

Trying to structure a plan to create a solid foundation of incremental learning is a challenging task for any non-trivial topic. When it comes to Swift and Cocoa/Cocoa Touch with its vast range of potential interests, ask the questions: “What core concepts and patterns best reward the language learner with immediate benefit?”, “What grouping conventions should be tossed overboard to better focus on the skills with highest returns?”, and “What critical paths allow learners to proceed towards measurable skills and performance with the least overhead?”

Justify each topic with an answer that’s not “it’s covered that way in the Swift Programming Language book”, especially when working with new learners versus developers moving into the language with existing programming experience. And even when teaching more experienced students, let the daily realities they’re trying to move towards mold the curriculum of what you choose to teach.

The best learners teach themselves. The best curriculum sets them up to do so.

Swift 5 gives us Nice Things™: Custom string delimiters

Say, for whatever reason, you were in desperate need of Bill the Cat ASCII art in your app. Maybe you were very drunk and had a bet. Maybe you were working with some kind of Unix awk client. I dunno. Let’s just start with the proposition that this was a real and meaningful challenge in your life.

In Swift 4.2, you could use multiline triple-quoted strings. Multiline strings are great for preserving indentation and other formatting, plus as a bonus, you get embedded quotes for free. Let me show you an example of how this works.

Instead of:

"\"I don't think...\"\n\"Then you shouldn't talk,\" said the Hatter."

with its multiple escape sequences, Swift 4.x gave us:

    "I don't think..."
    "Then you shouldn't talk," said the Hatter.

Same results, less fuss. The triple-quote string delimiter replaces the one-quote, so you don’t have to use backslash escaping. Dialog flows freely in 4.x.

But what happens when your source uses backslashes, as does this Bill the Cat clip art?

// error: invalid escape sequence in literal
let billTheCat = """
<------- ____
  &&&    /    \  __ _____,
    `-- |  o   \'  `  &&/
       `|      | o  },-'
         \____( )__/
         ,'    \'   \
 /~~~~~~|.      |   .}~~~\
  ,-----( .     |   .}--.
        | .    /\___/
         `----^,\ \

Nearly every backslash triggers a compiler error as an invalid escape sequence. The others are subsumed into an unintentionally valid escape (like \'). You have inadvertent line escaping at the ends of the seventh and eighth lines as well.

You have to escape each backslash, losing the ability to evaluate your clip art source at a glance. Every escape pushes characters on that line one item to the right. Given that this is Bill the Cat, not much is lost aesthetically speaking, but the results are less maintainable and harder to visualize.

let billTheCat = """
<------- ____
  &&&    /    \\  __ _____,
    `-- |  o   \\'  `  &&/
       `|      | o  },-'
         \\____( )__/
         ,'    \\'   \\
 /~~~~~~|.      |   .}~~~\\
  ,-----( .     |   .}--.
        | .    /\\___/
         `----^,\\ \\

The problem becomes more pronounced when you work with pre-escaped material instead of visual art. For example, you may have escaped JSON or XML you want to paste directly into an app’s string. Each stringity escape sequence is an error waiting to happen:

{\r\n  \"first_name\": \"John\",\r\n  \"last_name\": \"Smith\",\r\n  \"is_alive\": true,\r\n  \"age\": 27,\r\n  \"spouse\": null\r\n}

Enter Swift 5. Its custom delimiters work on escape sequences the way that multiline strings work on dialog. Just add a pound sign (#) to each end of your string and your backslashes are perfectly preserved without hand edits or audits:

// Perfect Bill
let billTheCat = #"""
<------- ____
  &&&    /    \  __ _____,
    `-- |  o   \'  `  &&/
       `|      | o  },-'
         \____( )__/
         ,'    \'   \
 /~~~~~~|.      |   .}~~~\
  ,-----( .     |   .}--.
        | .    /\___/
         `----^,\ \

Those extra pounds allow you to change the way Swift interprets escape sequences. They transform escapes from simple backslashes to \#. To insert a newline into a pound-delimited string, you type \#n and not \n. Similarly, string interpolation becomes \#(...interpolation...).

This system was inspired by the Rust programming language. Rust stacks one or more pounds at each end of a string (and prefixes the letter “r”) to create what it calls “raw strings”, that is strings without further escape sequence interpretation.  You cannot incorporate interpolation or coded tabs, new lines, or returns.

Swift adopts the extensible delimiters (skipping the ugly “r”) but retains its useful escapes, including string interpolation. Swift adapts each escape sequence to match the number of pound signs used at the start and end of the string. Instead of “raw strings”, Swift has, well, let’s call them “medium rare strings”. It allows you to paste and preserve raw formatting while retaining the ability to insert escape sequences.

In Swift 5, each of the following declares "Hello", even though they use a variety of single and multiline styles:

let u = "Hello" // No pounds
let v = #"Hello"# // One pound
let w = ####"Hello"#### // Many pounds
let x = "\("Hello")" // Interpolation
let y = #"\#("Hello")"# // Interpolation with pound
let z = """ // Multiline
let a = #""" // Multiline with pound

Here are the rules:

  • You must match the number of #-signs before and after the string, from zero to however many. “One” is almost always the right answer for “however many”.
  • When you use #-signs, you change the escape sequence from a single backslash to a backslash infixed with the same number of pound signs. A ##"Hello"##  string uses the \## escape sequence.
  • Anything that doesn’t match the closing delimiter is part of the string. To add """ to a multiline string without escaping, just change the delimiter with pound.
  • Use the least number of pound signs required for the results you need. Zero is best. One is fine. Two or more is very, very rare.

And that’s it. With this one small change, anyone writing code generation apps like PaintCode or Kite Compositor (or one of my many utilities), writing network code with escaped-JSON,  or including weird Bill the Cat clip art, can paste and go. Just add pounds as needed, without sacrificing the convenience of string interpolation or escape sequences.

SE-0200, which introduces this new behavior, is one of my favorite proposals I’ve ever worked on. I’ve been lucky enough to have had a working toolchain with these features (thanks John H!) since before the proposal was even adopted.  I can’t wait until Swift 5 debuts, allowing custom string delimiters to become part of everyone’s coding work as well.

Musing on API names for trailing and functional closures

When a call returns a value, I almost always use in-line closures. I prefer to surround functional calls with parens. I know my style is not universally popular, as many developers prefer the look of raw braces. It’s not uncommon to see calls like this:

numbers.sorted { $0 < $1 }.forEach {

The functional sort is chained to the non-functional loop, both using braces. Mandatory functional parens do two things. They differentiate expressions and they add the clarity of role labels that are lost with trailing closures. Compare these with the preceding call:

numbers.sorted(by: { $0 < $1 }).forEach {

// or even

numbers.sorted(by: <).forEach { print($0) }

In each case, the combination of name and label (in this case, sorted(by:)) is clearer and more easily read. Many APIs are designed without initial labels for Void-returning closures. They’re intended from the start to act as language-like constructs, so adding labels is either superfluous or detracts from the call when omitted:

public func forEach(_ body: (Self.Element) throws -> Void) rethrows

Omitting labels shouldn’t cloud intent even when a closure meant for functional calls is used. I could imagine common API naming rules to help guide labels and functional use (for example, “omit labels for Void-returning closure arguments” or “include role hint labels for functional closure arguments used to process and pass through values”).

Such rules might help but there’s one class of closures that doesn’t normally follow. Completion handlers, especially those sourced from Cocoa and Cocoa Touch, are almost always labeled as completion or some close variant. They’re designed for non-returning (and often asynchronous) execution. For example, you might see:

func run(_ action: SKAction, completion block: @escaping () -> Void)


func dataTask(with: URL, completionHandler: (Data?, URLResponse?, Error?) -> Void) -> URLSessionDataTask

These items are normally called as trailing closures, so why shouldn’t their API naming follow suit? Wouldn’t it make more sense to have _ completionBlock: or _ completionHandler: than to use explanatory labels that are most commonly hidden when called?

What do you think? Let me know.

ISO-8601, YYYY, yyyy, and why your year may be wrong

The end of the year is rolling around and it’s time to remind everyone about that yyyy works the way you think it does and YYYY does not. Here’s a quick example to start:

Just because you test a format quickly with the current date and get back the result you expect, does not mean you’ve constructed your date format correctly.

Speaking of which, BJ Homer points out that you can just use “y”, as “yyyy” pads to 4 digits which doesn’t usually matter but isn’t always needed. Olivier Halligon adds, further, that not all calendars use 4 digit years. “For example the Japanese start a new era every time the emperor changes, resetting to year 1 in that era; we’re currently in year Heisei 30.”

To quote The Dave™: “Nooooooo…. Please use “y”, not “yyyy”. “yyyy” zero-pads years that aren’t four digits, and there are multiple calendars w/ 2 or 3-digits years (Japanese, Chinese, Republic of China). “y” is the natural length of the year: “30” for Japanese cal, “2018” for Gregorian, etc”

What you’re actually seeing with “Dec 24, 2017” is the first day of the last full week of the preceding year. It doesn’t matter what numbers you plug into the month (“MM”) or day (“dd”). The presence of YYYY in the date format without its expected supporting information reduces to “start of year, go back one week, report the first day”. (I’ll explain this more in just a little bit.)

Here are some examples, which you can check from the command line using the cal utility:

As Apple’s 2014-era date formatting guide points out:

A common mistake is to use YYYY. yyyy specifies the calendar year whereas YYYY specifies the year (of “Week of Year”), used in the ISO year-week calendar. In most cases, yyyy and YYYY yield the same number, however they may be different. Typically you should use the calendar year.’s Unicode Technical Standard #35, Date Format Patterns goes into a little more depth:

[“Y” is] Year (in “Week of Year” based calendars). This year designation is used in ISO year-week calendar as defined by ISO 8601, but can be used in non-Gregorian based calendar systems where week date processing is desired. May not always be the same value as calendar year.

ISO 8601 uses a 4-digit year (YYYY) for “week of year” calendars from 0000 to 9999. If you’re into trivia, the years before 1583 are technically excluded except by special agreement between sending and receiving parties.

Anyway, if you’re going to use YYYY formats, you’ll want to use additional format elements that support “week of year” date construction. For example, consider the calendar for this upcoming January, which starts on Tuesday the 1st:

    January 2019      
Su Mo Tu We Th Fr Sa  
       1  2  3  4  5  
 6  7  8  9 10 11 12  
13 14 15 16 17 18 19  
20 21 22 23 24 25 26  
27 28 29 30 31

This year, January first can be considered as the first week of 2019 or the 53rd week of 2018, as the weeks overlap in the middle. Using e (the numeric day of the week) and ww (the ordinal week to count from), you can represent both dates correctly using the oddball YYYY formatting token.

Here are examples that use the week-of-year approach counting from both 2018 and 2019:

As you can see from this, when you use YYYY and do not supply an ordinal week or day, they both default to zero, which is why you get the behavior of the zeroth week (that is, the week before the first week) on the zeroth day (also, the first day of that week) for that calendar year, which is the week before the first week that overlaps the stated year. This explains the results of all those otherwise random late-December dates from earlier.

ISO 8601 should be updated in a few months, with a release somewhere around February.

From what I can tell, the first part revises the current standard and the second expands it. The only freely accessible human-viewable material I could find were the five-page TOC previews for 8601-1 and 8601-2.

(Hat tip: Thanks, Robin Malhotra)