Archive for February, 2018

Better initializers and defaulted arguments: Part II

As a number of people pointed out, using keypath initialization for uniform type members has its bright spots and its drawbacks. The particular use-case I wrote about (UIEdgeInsets) has four same-type members, and two common approaches: set all insets to the same value and set the vertical and horizontal inset values in tandem.

Because of this specific extension (adding vertical, etc members), you  open the door to potential bugs, namely:

let insets: UIEdgeInsets = [\.horizontal: 8, \.left: 4]

In this example, the developer intent is unclear. Should the left inset override the horizontal choice? Or should this be disallowed or warned? This occurs almost entirely to (my) bad design in letting \.horizontal and its fellow compound members act as initializer choices. Get rid of the compound settable members, get rid of the problem.

A similar bug occurs like this:

let insets: UIEdgeInsets = [\.left: 4, \.right: 4, \.left: 8]

Since there’s no checking in this approach, you can easily duplicate entries without the compiler warning or emitting an error. The Swift compiler does not complain about duplicate keys in dictionary literals (SR-7066). Aside from that, it’s a cute way to do an unconventional memberwise initialization but one that probably should never make its way into production code.

So what would be a better choice for this example? A custom initializer wouldn’t hurt. For example (and I’m not sure the tests against zero are helping or hurting performance here):

extension UIEdgeInsets {
    public init(all: CGFloat = 0) {
        self.init()
        if all != 0 { (top, bottom, left, right) = (all, all, all, all) }
    }
     public init(vertical: CGFloat = 0, horizontal: CGFloat = 0) {
        self.init()
        if vertical != 0 { (top, bottom) = (vertical, vertical) }
        if horizontal != 0 { (left, right) = (horizontal, horizontal }
    }
}

This gives you two convenience initializers specific to common use cases. You could alternatively write some kind of static method that builds an instance (something like UIEdgeInsets.inset(by:)) but I don’t think that gets you anything big beyond normal initializers.

Getting back to using dictionary literals, someone asked if you can use the same approach to create ad-hoc, unordered, type-erased member initialization. I’m leaning towards “no” but you might be able to play with some kind of Initializable protocol (ensuring init()) and then looking up the value for each keypath and grab a type from that. It would be a pain.  If you do get something like that working, drop me a note. At the least, it would be “unSwiftlike” and antithetical to type safety.

Betas, Damned Betas, and 11.3

After spending an eternity trying to connect to WiFi and my Apple ID after updating to the latest beta, I googled and discovered I wasn’t alone. A short while reading posts later, I downgraded to 11.2.5 and removed my beta profile from my iPad.

Here’s why: I could sign into my Apple ID in Safari but not Settings, and I was in an eternal loop of “you need to accept terms and conditions”-sign in-invalid password. I wasted an entire afternoon on this nonsense.

To save you (some) trouble:

  • Enter DFU Mode (hold power & home forever until the connect to iTunes appears)
  • Option-click Upgrade/Update (whatever it is) in iTunes rather than restore.
  • Navigate to the actual ipsw download (sorry, no easy “preferred” update), select it, wait for it to download a really really big file.
  • Go through the endless set-up again, cursing the day you chose  really secure long involved passwords for all your services.
  • ???
  • Profit

I’m going to hold off on new betas until June. What a pain. I hope this helps someone. Let me know.

Better initializers and defaulted arguments

Yesterday, I was discussing initializing UIEdgeInsets. Developer Adam Sharp cleverly added computed properties to leveraging keypaths by extending the type to adopt ExpressibleByDictionaryLiteral:

extension UIEdgeInsets: ExpressibleByDictionaryLiteral {
    public typealias Key = WritableKeyPath<UIEdgeInsets, CGFloat>
    public typealias Value = CGFloat
    
    public init(dictionaryLiteral elements: (WritableKeyPath<UIEdgeInsets, CGFloat>, CGFloat)...) {
        self = UIEdgeInsets()
        for (inset, value) in elements {
            self[keyPath: inset] = value
        }
    }
}

This approach lets you use a dictionary literal to initialize your type:

let insets: UIEdgeInsets = [\.left: 8]
print(insets) // (l: 8.0, r: 0.0, t: 0.0, b: 0.0)

Pop in a few custom properties, specifically horizontal, vertical, and all, and you have a really cute way of initializing edge insets without building a plethora of custom initializers, keeping the API boundary (Thanks Daniel J) nice and compact:

public extension UIEdgeInsets {
   public var vertical: CGFloat {
        get { return 0 } // meaningless but not fatal
        set { (top, bottom) = (newValue, newValue) }
    }
    
    public var horizontal: CGFloat {
        get { return 0 } // meaningless but not fatal
        set { (left, right) = (newValue, newValue) }
    }
    
    public var all: CGFloat {
        get { return 0 } // meaningless but not fatal
        set { (vertical, horizontal) = (newValue, newValue) }
    }
}

Unfortunately, you must supply a getter: a WriteableKeyPath is a “key path that supports reading from and writing to the resulting value.” (Emphasis mine.) That’s why I included the silly return 0 statements for each getter. I originally put in a fatal error but that only got me grief because the values were being read before writing.

Incidentally, Swift does not allow you to build a write-only type for compound abstractions like these. Just in case you were thinking of going that way with your code, here’s what you can expect:

With the dictionary-initializable approach, you may use a dictionary literal with as many or as few key paths as you need to fully customize your instance:

let insets2: UIEdgeInsets = [\.vertical: 8, \.horizontal: 20]
print(insets2) // (l: 8.0 , r: 20.0, t: 8.0, b: 20.0)

let insets3: UIEdgeInsets = [\.all: 8]
print(insets3) // (l: 8.0 , r: 8.0, t: 8.0, b: 8.0)

Stephen Celis notes, “The nice thing about key paths are they’re compiler generated code. you can write a single initializer function and get everything for free without having to define one-off enums or initializers every time.”

This approach is generally useful enough that it’s worth abstracting out a little to support dictionary literal initialization for any type with uniformly-typed property members such as CGRect or CGPoint. Nate C came up with a very clever approach to do exactly that. Here’s a modified version of his approach:

/// Allows dictionary literal initialization for any
/// conforming type that declares `typealias Value`,
/// where `Value` refers to a uniform property Type
/// that can be set through a keypath-value dictionary
///
/// - Example:
///   ```
///   extension CGPoint : UniformKeypathInitializable {
///     public typealias Value = CGFloat
///   }
///
///   let p: CGPoint = [\.x: 0, \.y: 20]
///   ```
public protocol UniformKeypathInitializable : ExpressibleByDictionaryLiteral {
    /// Allow zero-argument initializer
    init()
    
}

extension UniformKeypathInitializable {
    /// Initializes each member of a keypath-value
    /// dictionary, allowing the type to be initialized
    /// with a dictionary literal
    public init(dictionaryLiteral elements: (WritableKeyPath<Self, Value>, Value)...) {
        self.init()
        for (property, value) in elements {
            self[keyPath: property] = value
        }
    }
}

You provide a typealias for `Value`, which in this case means the type of the values supplied in the dictionary, and the magic happens for you.:

extension UIEdgeInsets: UniformKeypathInitializable {
    public typealias Value = CGFloat
}

That’s all it takes. Add the custom compound properties and you’re good to go.

Interestingly enough, during this process, I came across possibly the most inscrutable Swift error message ever (which I believe is saying something). Here’s one of my early attempts before I found Nate’s solution, and the error it produced:

Gotta love Swift.

Anyway, if there are errors in the post, fixes, improvements, or suggestions (and you know there always will be), let me know. Email, tweet, comment, whatever you like. Thanks as always!

Carrying user-sourced code forward in Swift Playgrounds for iOS

Had a really neat challenge today, as a Slack-buddy attempted to work with Apple’s exquisitely insufficient Playground Book documentation. His goal was simple: he wanted to be able to incrementally grow and test code from page to page, copying the user’s work as they moved on.

In theory, Swift Playgrounds for iOS enables you to build books where your reader/student incrementally builds code. Each page introduces a new concept, a new tweak, or a new approach. It’s a great way to layer each lesson on a previous take, or to take one lesson and branch it out to multiple endpoints.

You can either build, build, build to one big story or take one core concept and show many different ways to apply it. Either way, you want to be able to bring code — whether from the most recently edited page or from a shared core page — forward, so the reader/student can further engage with it, edit it, and make it fit with each page’s challenge.

Implementing “code forwarding” (I just made up that term) proved trickier than expected. Playground book workflow is often “understood” (that is, you have a deep understanding of what’s required because you’ve worked with it a lot or you’ve poked around at Apple’s examples or reversed engineered to see how things work) rather than explained step by step in the official docs. Because of this, he ran into several roadblocks along the way.

  • First among these, is that Apple does not provide a Playgrounds Book Author tool for Mac. You have to build your books by hand, going through the specs and hoping that each iteration works. Most of the time it does. Sometimes, maddeningly, it does not.
  • Second, you have to transfer the book to the iPad for each test (I use AirDrop™), and guess at what went wrong if it doesn’t work. When testing a series of book-based exercises, you have to either hard-code each “success” sequence (and there’s no way to set a “I am debugging/developing this book” flag) or actually do the coding, which can take a lot of time, especially if you’re debugging page 7 and you have to work through the exercises on page 1 – 6 for each test of page 7.
  • Finally, if your book is even a little out of spec with what Swift Playgrounds for iOS expects, it’s going to die without much feedback or explanation, leaving you scratching your head, cursing Dev Tools (but we really love you guys, we do), or otherwise venting frustration.

I wasted a bunch of hours because I wanted to make this work. And finally, I managed to get things working to my satisfaction. I thought I’d take the time to write things up to save you some bother. Here are a few things I learned while deep diving into today’s experiments.

The Zen of User Code

Code-forwarding allows you to propagate user-sourced/user-edited code from an earlier page in a playground book to a later page in a playground book. When you code-forward from a “source” to a “destination”, Swift Playgrounds for iOS makes a copy of the earlier code and places onto the current page.

That code is copied once and you aren’t given the option to re-copy unless you reset the page. Every page in Swift Playgrounds offers a reset option in the ellipsis menu, but its discoverability is low. Apple expects each reader/student to work through exercises linearly, progressing only when each previous problem is solved. This means that you don’t get “live” updates by popping back and making new changes to the source page. The destination copies once.

That also means you cannot apply code-forwarding until your page is set as complete. By “complete”, I mean that the book’s source code and Swift Playgrounds accept that the reader/student has done sufficient work to move forward and progress to the next page/exercise.

This usually happens by executing a page epilogue. The epilogue tests the state of the page’s data, determines if the problem was solved (for example, whether the robot reached the end square and the code progressed to a hidden portion containing this test), and then updates a user assessment. Unless a page’s assessment status is “passed” (that is, done), the reader/student is not offered code copying on the following page.

This is built into Swift Playgrounds for iOS, and is an underlying assumption on how progressive learning plans operate. It’s a critical pathway for building page-by-page progress and enabling code-forwarding. This is why the following snippet includes its bit of hidden code. This code allows a user to pass, that is receive a passing grade/assessment for the page, without doing any more work than running the current page:

//#-copy-source(id1)
//#-editable-code 
func foo() {
    // ... starter code here
}
//#-end-editable-code
//#-end-copy-source

//#-hidden-code
import PlaygroundSupport
PlaygroundPage.current.assessmentStatus = 
    .pass(message: "Great job!")
//#-end-hidden-code

Building Code-Forwarding

The preceding code incorporates two essential parts of using a copy-source markup area.

  • First, is the actual tagged copy-source code. This delimits the code that gets copied forward to one or more other pages. Make sure to mark it editable when you want to present a challenge requiring end-user-reader modification. You can omit editable tags when you want the next step or branches to start with code you source yourself. It’s an unusual approach but it’s not illegal to do so.
  • Second, is the hidden assessment update. Normally you’d use more sophisticated logic to determine whether a reader/student has met those challenges laid out in the current page before allowing them to .pass or .fail. When you just want to demonstrate core functionality, make it clear in your marked-up write-up that the user must run the code before continuing. Use the approach in this code to “pass on first run” for demonstration. You’ll probably want to update the message to something along the lines of “Great! You’ve seen this work, move to the next page to start making changes.”

Building The Destination

Crafting a destination page is trickier than laying out acopy-source area: You must update your page’s manifest as well as its content source. The manifest will expect properly internationalized source strings. That means at a minimum, a code receiving page will need a Contents.swift file, a Manifest.plist file, and a PrivateResources folder with at least one localized lproj folder (in my case, en.lproj), which in turn holds the ManifestPlist.strings file.

Here’s what a simple manifest looks like for a copying destination. Keep in mind that each value entry for the CodeCopySetup keys is actually a placeholder for localization.

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CodeCopySetup</key>
	<dict>
		<key>CopyCommandButtonTitle</key>
		<string>CopyCommandButtonTitle</string>
		<key>DefaultCommandButtonTitle</key>
		<string>DefaultCommandButtonTitle</string>
		<key>NavigateCommandButtonTitle</key>
		<string>NavigateCommandButtonTitle</string>
		<key>NotReadyToCopyInstructions</key>
		<string>NotReadyToCopyInstructions</string>
		<key>ReadyToCopyInstructions</key>
		<string>ReadyToCopyInstructions</string>
	</dict>
	<key>Description</key>
	<string>Description</string>
	<key>LiveViewEdgeToEdge</key>
	<true/>
	<key>LiveViewMode</key>
	<string>VisibleByDefault</string>
	<key>MaximumSupportedExecutionSpeed</key>
	<string>Fastest</string>
	<key>Name</key>
	<string>Name</string>
	<key>PlaygroundLoggingMode</key>
	<string>Off</string>
	<key>Version</key>
	<string>1.0</string>
</dict>
</plist>

I followed Apple’s example in my ManifestPlist.strings file, so the English expressions aren’t terribly exciting. The Name field used in the manifest is spelled out in addition to the button text:

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
	<key>CopyCommandButtonTitle</key>
	<string>Copy My Code From the Last Page</string>
	<key>DefaultCommandButtonTitle</key>
	<string>Start Coding on This Page</string>
	<key>Name</key>
	<string>Copying Text from the Previous Page</string>
	<key>NavigateCommandButtonTitle</key>
	<string>Return to Previous Page</string>
	<key>NotReadyToCopyInstructions</key>
	<string>Be sure to complete the previous page before you move on to solving the next step.</string>
	<key>ReadyToCopyInstructions</key>
	<string>You can bring over your algorithm from the previous page to continue improving it.</string>
</dict>
</plist>

Here, each possible assessment state and action is given a human-readable form. I was unable to make the system “default” to the items mentioned in the Playground Page Manifest documentation (such as “Copy my code” and “Start with provided code”). I’m sure if I tried hard enough, I could have gotten this working per the docs but I didn’t have the time to push.

In building the code-destination contents, link each identifier you used in the source (it’s id1 in this example but it can be any key you want to use) and the page to copy from (Page1). This page names comes from the name of the playgroundpage file hosting the user-edited or user-sourced content.

You must mention the page because you may keep enhancing the same progression of code from page to page, while using a single identifier. If you start on page 1, update on page 2, when you get to page 3, you want to copy from the updated source on page 2, not page 1. Mentioning which source you want to copy helps keep you and the user on track.

//#-editable-code
//#-copy-destination("Page1", id1)

//#-end-copy-destination
//#-end-editable-code

If you’re using a branching storyline (for example, you might explore variations on a sort or showcase different blending modes for merging images), you can place this destination code on each branch page.

More often, you’ll want to progressively modify code through a series of exercises. To carry the code further, add copy-source tags around the destination as in the following code, using the same id1 identifier, and refer to #-copy-destination("Page2", id1) for the next copy on Page 3 and so forth. Read this directive as this is the copy destination for the code tagged with id1 sourced from page 2.

Here’s what an edit-and-carry approach looks like for a second page, referring back to ("Page1", id1). In my imagination, this is the first time code has been copied and this markup sets up a user-editable progression that can be carried to the third page and beyond.

//#-copy-source(id1)
//#-editable-code
//#-copy-destination("Page1", id1)

//#-end-copy-destination
//#-end-editable-code
//#-end-copy-source

That’s pretty much all you need: proper tags, proper localized strings, and proper id/page references. If you’d like to try out a copy of my playground, you can grab a copy from here or email me for a copy if that doesn’t work.