Archive for the ‘Development’ Category

Dear Erica: How do I simplify `Swift.print`?

Dear Erica:

In other languages (Python mostly comes to mind, but I think ml and probably Haskell as well) you can essentially create a new name for a function by assigning it to a variable and use that instead.  All type information and usage follows with it.

I use it a lot in Python to have a local variable that’s  already bound to some otherwise nested module call. It saves some lookup time and textual typing. (Gotta be explicit since syntactic typing is relevant in Swift.) In trying to work around the problem of “print” calling  NSDocument.print, I tried declaring a val at the top level:

let Print = Swift.print // for print to console

The compiler seemed happy with the definition but when I tried to use it as in:

Print(“in makeWindowControllers”)

I got:

Hitting Fix did nothing but I wasn’t really expecting much (this is Xcode 9.0 beta). I assumed it wasn’t  telling me to literally put <#String#> in as a second parameter but that the type inference was inferring a type of String for  parameter #2  It didn’t really make any sense (why would a second parameter be required for a variadic argument?) If two, why not 3…?

So I tried the following but to no avail:

Print(“in makeWindowControllers","two”)

One can obviously write a full function which works fine:

func Print(_ items:Any...) -> () {
    print(items) 
} 

Print("in makeWindowControllers")

It’s pretty simple but seems unnecessarily heavyweight. I can’t seem to find any way to do a variadic closure. Is this possibly a bug or am I missing something obvious? Is there any reason the simple value declaration shouldn’t work? I know I’ve seen complaints about the lack of an Apply function in Swift. Not sure if this is related. My functional mojo is somewhat lacking…

This is a terrific question, and I’m going to answer it in several parts.

First, the full signature of Swift’s version of print is

public func print<Target>(_ items: Any...,
    separator: String = default, 
    terminator: String = default, 
    to output: inout Target) 
    where Target : TextOutputStream

See all those default items?  They don’t travel nicely to closures.  Second, take careful note of the variadic items, because you can’t pass them along by redirecting them to another function. Your “full function” actually prints an array of the items you pass:

Print("Hello world") // prints ["Hello World"]

The only way around this for 10.12 and earlier is to re-implement print (or a reasonable facsimile). Having tried that this morning, I warn you, it is a doozy. Seriously. You wouldn’t believe how many functions and files go into this one little call.

Fortunately, this name-overlap problem (NSView.print vs Swift.print, etc) is fixed in High Sierra. The 10.13 release notes write:

print() methods in Swift: NSWindow, NSView, NSDocument’s print() instance methods have been renamed to printWindow(), printView(), and printDocument() respectively in Swift 4. This fixes the unexpected experience where adding debug logging to a subclass of one of these instances shows a print panel instead.

You can help the variadics don’t propagate cause (“El viva variadics!“) by filing a radar. Go ahead and dupe, mentioning rdar://problem/12134482.

For the moment, here’s a less capable workaround you can use. It does pretty much what you want with slightly reduced capabilities (and complexity) compared to the built-in Swift.print solution.

public func sprint(
    _ items: Any...,
    separator: String = " ",
    terminator: String = "\n")
{
    var prefix = ""
    for item in items {
        Swift.print(prefix, terminator: "")
        Swift.print(item, terminator: "")
        prefix = separator
    }
    Swift.print(terminator)
}

It’s kind of a production-unfriendly workaround for just avoiding Swift.print, but I hope this helps anyway.

Thanks Dave, Tim, Stephen, Caleb

Beta 3 Playground Workarounds

Adding Resources and Sources folders to Playgrounds

Until they’re fixed, you may have to add them by hand.

  1. Right-click/control-click.
  2. Show package contents
  3. You can add new Resources and Sources files at the top level
  4. Alternatively, navigate down to individual pages (which are finally in Beta 3!) by showing their package contents and add them there

Fortunately under Beta 3 you don’t have to manually add pages, as the new page functionality is finally back.

Creating New Playgrounds

They’re no longer listed in the File > New dialog. Instead choose File > New > Playground (Command-Shift-Option-N) or open “Welcome to Xcode” (Command-Shift-1) and click “Get started with a playground”.

Most of the obvious alternatives (like Command-Control-N, which creates new workspaces) are already taken, but if you don’t mind using the menu for that, I think it’s a nicer key binding for “New Playground”. If you want to mess with this open prefs (Command-comma), type playgrounds into the search field, and edit the key binding for “New > Playground”

Don’t forget that new playground page is “Command-Option-N”.

The Perfect QA Recruitment Filter

Have you ever heard of the “Brown M&M” clause? The band Van Halen used to issue a contract rider for its shows. In it, they requested a supply of M&Ms for backstage but specifically excluded any brown ones. Van Halen reserved the right to cancel the show if any  brown M&Ms were found.

Superficially, this may sound like a particularly obnoxious and entitled rock star request. However, there was a deeper motivation for this contract stipulation. As articles in recent years have revealed, Van Halen’s “no brown M&Ms” clause acted as an early warning system that alerted the band about potentially unsafe venue conditions.

Steve Jones of Entrepreneur writes:

In now-departed arenas such as Toronto’s Maple Leaf Gardens, the original Boston Garden and Chicago Stadium, Van Halen was loading in massive amounts of staging, sound equipment and lighting. Unfortunately, these buildings were never built to accommodate a rock band of Van Halen’s scope. Without specific guidelines, old floors could buckle and collapse, beams could rupture, and the lives of the band, their crew and fans could be at serious risk.

To ensure the promoter had read every single word in the contract, the band created the “no brown M&M’s” clause. It was a canary in a coalmine to indicate that the promoter may have not paid attention to other more important parts of the rider, and that there could be other bigger problems at hand.

Whenever the band found brown M&M’s candies backstage, they immediately did a complete line check, inspecting every aspect of the sound, lighting and stage setup to make sure it was perfect.

This kind of smart business check isn’t limited to large-scale traveling productions. JF Poole of Primate Labs was telling me the other evening about a similar approach he uses for recruiting Quality Assurance engineers.

“What I love,” he said, “is that pretty much every cover letter we’ve received for the position has cited the candidate’s ‘great attention to detail’ but almost none of them include the candidate’s favorite primate.”

Odd detail, right? But Primate Labs specifically asks for that as part of their recruitment process. The job listing says, “Please, mention your favorite primate in your cover letter.” For a position whose foundation is careful adherence to detail through every stage of production, it’s the perfect test.

Like Van Halen’s brown M&M’s, the recruiters at Primate can quickly scan incoming applications for one unique signifier. Even better, that request tests a candidate’s intrinsic suitability for the position: a rigid and fanatical adherence to detail. When an applicant doesn’t pay attention to the job listing, they probably won’t pay proper attention to your software. It’s a genius approach.

In some cases, sophisticated tells aren’t exactly needed (for example,  “I, $NAME (sic), have come across an opportunity for the position of Software QA Analyst for your esteemed company.“) but it’s helpful to adopt a quick indicator, allowing HR to set aside resumes for more serious consideration.

When I mentioned how sad I was that I couldn’t write up a post about this, John assured me that it would be okay. (“You’re overestimating the set of people who would a. read your blog, and b. apply for our job. Go for it.”) Can you think of any other job category that can so easily hide stealth “tells” for qualifications outside of, maybe, “profreader” (sic) and other consistency-driven positions?

For what it matters, my favorite primate (outside of my husband and kids) is the Slow Loris. Isn’t it cute?

(image via International Animal Rescue)

Result types

How do I use result types? When using a Result enum for callbacks, how to access the Error?

The most common Result enumeration looks like this:

enum Result<Value> { 
    case success(Value), failure(Error) }

A Result is used almost exclusively in completion handlers. In synchronous code, it’s more common to use throwing functions rather than Result types:

do {
    let value = try throwingFunction(...)
} catch {
    ... handle error ...
}

A Result type replaces the (value: Value?, error: Error?) -> Void handler signature used by many Cocoa APIs with this single Swift enumeration. Handling this type requires a slightly different approach than you’d use with thrown error handling.

As a rule, if an error is generated on your behalf, pay attention to it and don’t discard it out of hand. Errors help identify underlying issues that you may be able to resolve. They also provide important information for the developer and end-user of why an operation has failed.

The switch statement provides the simplest approach to handle both result conditions with equal priority:

switch result {
case .failure(let error): 
    // handle error here
case .success(let value): 
    // handle success here
}

If the error handling code is significantly less detailed than the success code, you might choose to perform early exit instead of using switch. This approach allows you to handle any errors and then move on to processing the returned value at the top scope.

Use an if statement (not a guard statement) to bind error instances. Its primary clause should handle the bound error  and then leave scope.  If the result is success, the if-test will fail. Follow the error check with a guard statement to bind the success value.

if case .failure(let error) = result {
    // handle error
    return
}
guard case .success(let value) = result 
    else { fatalError("Success value could not be bound") } // this should never happen

// use value

This second approach allows you to promote the typically detailed steps involved in processing a value after extracting it from the Result enumeration. The guard‘s else clause is a little ugly but necessary. Swift doesn’t offer a “forced enumeration unwrap” similar to Optional‘s !.

Breaking the handling down into an if/guard pair is not as elegant as the unified switch statement, but it provides a practical way to promote the importance of the returned value.

Update: If the !! operator is ever adopted, you could extend Result to return a computed var value: Value? member, and then use !! instead of the guard/fatalError combo in the above example to create a streamlined early return / value handling approach:

if case .failure(let error) = result { ... }
let value = result.value !! "Success value could not be bound"

It’s a lot cleaner. See this PR for more details. (Thanks Dave)

Pronouncing “Tuple”

A tuple is a finite ordered list of elements. It is presented as a parentheses-braced, comma-delimited list. In Swift, you can use them as stand-alone heterogenous lists of values or pass them as arguments to functions and closures.

A tuple is pronounced “tupple” (TUH-ple), not “two-pull”. It’s a shortcut pulled from “double, triple, quintuple, sextuple, octuple”, etc. Yes, please note that “quadruple” doesn’t fit with the others and is not used as a basis for speaking the word. Rules about long and short “u”s that apply to other English words are also not relevant to this case.

In Swift, a tuple is analogous to an anonymous struct. Its members are indexed numerically (.0, .1.2, etc). You can also use labels to access members by name:

let point = (x: 5.0, y: 2.3)
print(point.1) // 2.3
print(point.y) // 2.3

Swift 3.0 and later no longer supports splatting, so you cannot decouple a tuple from a function call. You can read more about this in SE-0029, which disallowed the ability. Before the change, you could call a function either with its direct arguments or by passing a tuple:

func foo(a : Int, b : Int) {}
foo(a: 42, b : 17) // still allowed
let x = (a: 1, b: 2)
foo(x) // no longer allowed in Swift 3+

The continued work on SE-0110 is still resolving on how tuples and closures interact.

The word “arity” describes the number of members in a tuple. (It also describes the number of arguments or operands accepted by a function, method, or closure.) The examples above use an arity of 2. You can call this a “2-arity tuple” or the shortcut “2-ary tuple”. Some shorten that further to a “2-tuple”.  All are acceptable.

Some fun facts to finish with:

  • A figurative tuple with an arbitrary arity is an “n-arity” or “n-ary” or “n-tuple”.
  • A tuple with a variable number of arguments is variadic.

Lessons Learned: iOS Extensions and Keychain Accessibility

Today’s lesson is courtesy of Rizwan Sattar, who writes:

If you’re building a notification service or content extension, keep in mind that these extensions will run even after a device restart, before the first unlock. Normally Apple recommends to set your Keychain items as kSecAttrAccessibleAfterFirstUnlock for “items that need to be accessed by background applications”. When you’re accessing the keychain for things in your notification extensions, you’ll want to set it to kSecAttrAccessibleAlways or kSecAttrAccessibleAlwaysThisDeviceOnly, etc instead.

Thanks Rizwan!

Working with optional errors in completion handlers

Foundation likes to pass optional errors (versus, say, a unified Result type) to completion handlers. A typical closure uses a (Value?, Error?) -> Void signature,where Value is some sort of data result that varies by operation.

A colleague was struggling to use conditional binding along with casting in his handler. Leaving aside for the moment any rational need to cast to NSError, this is an interesting demonstration of how you perform these two operations synchronously in code.

A cast from Error to NSError is guaranteed to succeed, so you can use the as operator. However, you must phrase the cast just right. Otherwise the Swift compiler emits warnings, as you see in the following screenshot. Here is an example of how you don’t get this job done properly:

As my friend complained in frustration: “But it tells me “did I mean as” and when I switch `as?` to `as` then it complains that error is Error? and isn’t convertible to NSError.

This attempt followed the normal pattern of conditional casting. Swift automatically lifts double optionals into a single optional result when used this way, but the cast from Error to NSError will always succeed, so you can’t use as? here.

To resolve, use a non-conditional cast to NSError? and then perform conditional binding to unwrap the value:

enum Bad: Error { case luck }

let error: Bad? = Bad.luck

if let error = (error as NSError?) {
    print("Worked")
}

The parens around the non-conditional cast make all the difference. Swift removes its warnings and makes everything work as expected.

iOS 11 Screenshots

The new iOS 11 screenshot / edit feature has got to be my very favorite thing of the upcoming firmware update. Saving a screenshot creates a thumbnail in the bottom corner of the screen. Tap it to enter an edit mode that lets you crop and mark up the image.

  • Scroll left and right to move between screenshots if you’ve snapped more than one.
  • Use the blue handles on the sides and corners of the screenshot to crop the shot.
  • Select an editing tool (pen, highlight, pencil, eraser, lasso, and an assortment colors) then draw with your finger.
  • You undo-and-redo using buttons at the bottom left of the editor window (not shown here, because I hadn’t made any edits yet).
  • Tap Done at the top left to leave. You can save your shot to the photos album.
  • Otherwise, tap the action button (top right), to print, air drop, email, or otherwise work with your now-edited image.  I love the air drop option, which lets me snap, edit, and then throw the image into a blog post or a slack channel.

No wires, no fuss, just great convenience.

More on SE-0110: Important fallout, please read (Updated)


Update: Statement from Austin

…I’d like to appreciate my heartfelt thanks to everyone who reached out to me one way or another. It’s clear to me that the Swift, Apple platform developers, and swift-evolution communities are amazing, and that the people in them are kind, wonderful, generous, passionate, and caring. The Core Team in particular has done an incredible job shepherding the community, befriending people on and off the lists, and leading an open-source project of great technical and social complexity.

After thinking about things, I plan to continue participating in swift-evolution and looking for new ways in which I can serve the Swift and Apple developer communities. I hope to listen more, speak less, be more sensitive to other peoples’ feelings, and offer fair, well-considered feedback.


Often the Swift core team will ask for community help to develop and sponsor a proposal. I’ve worked on several of these. These proposals are generally aimed towards simplifying the compiler, enhancing the language, or addressing technical issues that place stumbling blocks in the effective delivery of compilation.

The reconsideration of SE-0110 should not reflect in any negative way on Austin Zheng. He worked hard on a proposal whose intent was to serve the large Swift developer community. I congratulate Austin for shepherding through this proposal, which can be a long, frustrating process.

The usability regression was unexpected. I applaud the core team for its flexibility in responding to the community’s real concerns when its implementation showed issues.

Today, Austin tweeted:

If my posting of the SE-0110 notice last night contributed to a negative atmosphere, I apologize. I have written to Austin and I hope he will reconsider his decision and rejoin Swift Evolution.

On the SE-0110 Regression (full text)

Doug Gregor writes:

Hello Swift community,

Swift 3’s SE-0110 eliminated the equivalence between function types that accept a single type and function types that take multiple arguments. However, for various implementation reasons, the implementation of SE-0110 (as well as the elimination of tuple “splat” behavior in SE-0029) was not fully completed.

 

Swift 4 implemented more of SE-0110, which caused a fairly serious usability regression, particularly with closures. Here are a few simple examples involving closures that worked in Swift 3 but do not work in Swift 4:
// #1: Works in Swift 3, error in Swift 4
myDictionary.forEach {
  print(“\($0) -> \($1)”)
}
 
// #2: Works in Swift 3, error in Swift 4
myDictionary.forEach { key, value in
  print(“\(key) -> \(value)”)
}
 
// #3: Works in Swift 3, error in Swift 4
myDictionary.forEach { (key, value) in
  print(“\(key) -> \(value)”)
}
Similar issues occur with passing multi-argument functions where a tuple argument is expected:
// #4: Works in Swift 3, error in Swift 4
_ = zip(array1, array2).map(+)
In all of these cases, it is possible to write a closure that achieves the desired effect, but the result is more verbose and less intuitive:
// Works in both Swift 3 and Swift 4
myDictionary.forEach { element in
  let (key, value) = element
  print(“\(key) -> \(value)”)
}

 

The Swift core team feels that these usability regressions are unacceptable for Swift 4. There are a number of promising solutions that would provide a better model for closures and address the usability regression, but fully designing and implementing those are out of scope for Swift 4.  Therefore, we will “back out” the SE-0110 change regarding function arguments from Swift 4.

 

Specifically, when passing an argument value of function type (including closures) to a parameter of function type, a multi-parameter argument function can be passed to a parameter whose function type accepts a single tuple (whose tuple elements match the parameter types of the argument function). Practically speaking, all of the examples #1-#4 will be accepted in both Swift 3 and Swift 4.

 

We will revisit the design in this area post-Swift 4.

 

– Doug