Archive for the ‘Challenge’ Category

Challenge: Filtering associated value enumeration arrays

The Challenge

Courtesy of Mike Ash, here’s the challenge. You have an enumeration:

enum Enum {
    case foo(Int)
    case bar(String)
    case qux(Int)

And you have an array of them:

let items: [Enum] = [.foo(1), .bar("hi"), .foo(2)]

Return a filtered array containing only one case, for example foo. The difficulty lies in that Swift does not seem to offer a == or ~= operator that works on cases, ignoring associated values:

// does not work
let filtered = items.filter({ $0 == .foo })

So what do you do?

Attempt 1

Here’s my first attempt. Super ugly but it gets the job done:

let filtered = items.filter({ 
    switch $0 { case .foo: return true; default: return false } })

Evan Dekhayser prefers if-case:

let filtered = items.filter({ 
    if case .foo = $0 { return true }; return false })

And you can of course use guard as well:

let filteredy = items.filter({ 
    guard case .foo = $0 else { return false }; return true })

Attempt 2

Just as ugly but slightly shorter in terms of number of characters. But it does more work than #1:

let filtered = items.filter({ 
    for case .foo in [$0] { return true }; return false })

Again, yuck.

Attempt 3

I really hate this approach because you have to implement a separate property for each case. Double yuck:

extension Enum {
    var isFoo: Bool {
        switch self { case .foo: return true; default: return false }
let filtered = items.filter({ $0.isFoo })

Attempt 4

This is gross because it requires a placeholder value for the rhs, even though that value is never used. And no, you can’t pass an underscore here:

extension Enum {
    static func ~= (lhs: Enum, rhs: Enum) -> Bool {
        let lhsCase = Array(Mirror(reflecting: lhs).children)
        let rhsCase = Array(Mirror(reflecting: rhs).children)
        return lhsCase[0].0 == rhsCase[0].0
let filtered = items.filter({ $0 ~= .foo(0) })

Attempt 5

Then I got the idea into my head that you could use reflection. If you don’t supply a value to an enumeration case with an associated value, it returns a function along the lines of (T) -> Enum. Here is as far as I got before I realized the enumeration *name* was not preserved in its reflection:

import Foundation

extension Enum {
    var caseName: String {
        return "\(Array(Mirror(reflecting: self).children)[0].0!)"
    static func ~= <T>(lhs: Enum, rhs: (T) -> Enum) -> Bool {
        let lhsCase = lhs.caseName
        let prefixString = "Mirror for (\(T.self)) -> "
        let typeOffset = prefixString.characters.count
        let typeString = "\(Mirror(reflecting: rhs).description)"
        let rhsCase = typeString.substring(from: typeString.index(typeString.startIndex, offsetBy: typeOffset))
        return true

Yeah. Really bad, plus it doesn’t work.

Call for solutions

Since I didn’t really get very far with this, I’m throwing this out there as an open challenge. Can you come up with a parsimonious, readable, and less horrible (I was going to say “more elegant”, but c’mon) way to approach this? I suspect my first attempt may be the best one, which would make me sad.

A few interesting things about iOS Swift Playgrounds

Misc rambles:

Interesting: You no longer “print” in iOS Swift Playgrounds. Anything that can be presented using a playground QuickLook or a custom string representation is done so with the tap-to-view item at the right. There’s no “printing” per se, no console, while I suppose you can import Foundation and NSLog stuff, I’m not sure how reasonable a solution that is, especially on the go.

Because: This morning I ended up importing AVFoundation to let AVSpeechSynthesizer “speak” feedback to me. Not ideal, but short and easy to implement, and got the job done for some stuff that wasn’t rendering nicely the way I needed it to, in a complicated playground book that was using SceneKit not UIKit.

Rad discovery of the day: Command-R runs the playground without having to tap the screen. \o/ Press and hold Command key (on a physical Bluetooth keyboard, this doesn’t work on, for example, type2phone) to discover other shortcuts:


Sad discovery of the day: You cannot air drop playground books anymore, and Swift Playgrounds is being very very careful about allowing you access to any material you didn’t create or import yourself. There’s no Documents support for iTunes. At the suggestion of Jonathan Penn, I gave it a try after rebooting and now it works. You wouldn’t believe how much time I wasted trying to extract information to look up implementation details.

Thanks again to Jonathan P for pointing me to the command-key discovery feature!

Swift By Emoji: A considered approach

Not too long ago Iain Delaney pointed me to this graphic:


The graphic was designed by Steve Luscher and written about by Joey Devilla in this blog post on Global Nerdy. I thought it was brilliant and inspiring.

It wasn’t written in Swift and certainly wasn’t running in Swift. I decided to play around: I built a playground, assigning massive lists of emoji strings to emoji variables, and got these examples running properly using Swift syntax.


Rather than use a pile of poo, which assumes at each stage of reduction you’re combining poo with a new food, I went with Jaden Geller’s recommendation on Twitter. In the Swift version, the reduction starts with a sad face and becomes happy and satisfied.

I played around with other foods to see if it was worth expanding the samples but it was never quite as clean or elegant as the simple 4-item original:


Stepping away from the cow/potato/chicken/corn space, I wanted to see if there might be a better filter than isVegetarian. A child makes amusing (if not nutritious) food choices:


And then I thought, well what about other Swift language essentials. So I mocked up the concept of naming items by whether they are mutating or non-mutating:


And repeating:


And sorted (although this one could probably use some better food choices):


Zipping was an obvious win as well:


And map vs flatMap:


Unfortunately, a soccer ball is not a valid character identifier so I couldn’t bitcast between a European football and an America one. Inconsistent Emoji character sets made me sad. Swift needs a standards-based operator and identifier makeover:


By the time I started playing with fatalError, I realized I was spending way too much time on this:


Do you have any favorite Swift functionality that lends itself to emojification? I’ve showed you mine. Now, show me yours.

Update: Phil Aaronson suggests using emoji functions too.

Ideally, examples should be able to compile and run in a Swift playground but I’m open to concepts that can be better explained with Emoji even when implementation is tricky.

Holy War: Enum Hash Values and Option Sets

I recently engaged in a conversation on the Swift Users list about converting a JSON array of string values into an enumeration set. I somewhat tongue in cheek suggested that these values be converted into an string-based enumeration, and then their hashValues be used to set-up flags.

I was, of course, immediately (and rightfully) challenged on whether a solution should hinge on the hashValue implementation detail — it shouldn’t. But the more I thought about this, I wondered whether it might be reasonable to eliminate potential errors by using the hash values to guide the option set creation.

Here’s what I mean. Consider this enumeration:

private enum LaundryFlags: String { 
    case lowWater, lowHeat, gentleCycle, tumbleDry }

You can use the enumeration to populate an option set, knowing each hashValue will not overlap, allowing the compiler to choose the implementation details without ever touching them yourself:

public static let lowWater = LaundryOptions(rawValue: 
    1 << LaundryFlags.lowWater.hashValue)

This approach allows you to build option sets from strings but not worry what the raw values are. Whatever the compiler picks will be consistent:

// String based initialization
public init(strings: [String]) {
    let set: LaundryOptions = strings
        .flatMap({ LaundryFlags(rawValue: $0) }) // to enumeration
        .map({ 1 << $0.hashValue }) // to Int, to flag
        .flatMap({ LaundryOptions(rawValue: $0) }) // to option set
        .reduce([]) { $0.union($1) } // joined
    _rawValue = set.rawValue

There are limits. You cannot use enumerations to represent compound convenience members like the following examples:

public static let energyStar: LaundryOptions = [.lowWater, .lowHeat]
public static let gentleStar: LaundryOptions = energyStar.union(gentleCycle)

On the other hand, you can adopt CustomStringConvertible pretty easily even though raw-value enumerations do not report their members and cannot be initialized from hash values. As the following code shows, it’s not a huge burden to generate a lazy member dictionary. You can boiler plate the implementation and copy/paste your case list into this array:

static var memberDict: Dictionary<Int, String> = 
    [lowWater, lowHeat, gentleCycle, tumbleDry]
    .reduce([:]) {
        var dict = $0
        dict[$1.hashValue] = "\($1)" 
        return dict

Reduce the dictionary with bit math from the option set:

public var description: String {
    let members = LaundryFlags.memberDict.reduce([]) {
        return (rawValue & 1 << $1.key) != 0
            ? $0 + [$1.value] : $0
    return members.joined(separator: ", ")

So here’s the holy war question: given how simple and reliable this approach is, do I back off of my “never use implementation details” guidance for raw value enumerations and their hash values?

Full gist is here.

Animating letters into place

I love playgrounds. This is exactly the kind of challenge they were built for. Joe Fabisevich asked: “Does anyone know how (or if) it’s possible to animate every character of a UILabel (or UITextView/some other text holding view if necessary)? I want to replicate this effect, of the word Hello!


If you want to read about this kind of UIKit fun, my Gourmet Cookbook covers a lot of it. The book is in Objective-C but it’s not hard to translate the tricks over to Swift.

Once you’re in Swift, you can easily put together proof of concepts and tweak parameters from a playground, with instance feedback — from speeding up and slowing down the animation, to testing out different font faces and color schemes.

Source Code

And another take, with a little fade in and scale popping:

Converting optionals to thrown errors

Soroush Khanlou writes: “Lots of times i just wish there were no optional type, and it was all just `Result`”

He gives this example:

struct NilError: Error { }

func throwable<T>( _ block: @autoclosure() -> T?) throws -> T {
    guard let result: T = block() else {
        throw NilError()
    return result

let image = try throwable(UIImage(data: imageData))

I decided to fancy it up a little:

// Inspired by Soroush Khanlou

public enum Throws {
    public struct NilError: Error, CustomStringConvertible {
        public var description: String { return _description }
        public init(file: String, line: Int) {
            _description = "Nil returned at "
                + (file as NSString).lastPathComponent + ":\(line)"
        private let _description: String
    public static func this<T>(
        file: String = #file, line: Int = #line,
        block: () -> T?) throws -> T
        guard let result = block() 
            else { throw NilError(file: file, line: line) }
        return result

do {
    let imageData = Data()
    let image = try Throws.this { NSImage(data: imageData) }
} catch { print(error) }

The obvious difference is that my errors look like “Nil return at playground13.swift:24” but I also added a few things according to some style choices I’m testing out:

  • No autoclosure. Reserve autoclosure for lazy evaluation. Apple writes, “The context and function name should make it clear that evaluation is being deferred.”
  • No global freestanding function. Embed globals into types as static members.
  • Nested error declaration. It’s a subordinate and specific to the type.
  • Custom description. The error tells you more about itself than just its name.
  • Allman after a multi-line complex initializer declaration.
  • Late private property declaration. I’m kicking the wheels on this, which I picked up from the Standard Library folk.


Update: Loic has a really nice alternative that inspired me to tweak:

public struct NilError: Error, CustomStringConvertible {
    public var description: String { return _description }
    public init(file: String, line: Int) {
        _description = "Nil returned at "
            + (file as NSString).lastPathComponent + ":\(line)"
    private let _description: String

extension Optional {
    public func unwrap(file: String = #file, line: Int = #line) throws -> Wrapped {
        guard let unwrapped = self else { throw NilError(file: file, line: line) }
        return unwrapped

do {
    let imageData = Data()
    let image = try NSImage(data: imageData).unwrap()
} catch { print(error) }

Style: How would you fold this?

Here’s the stdlib implementation of zip:

public func zip<Sequence1 : Sequence, Sequence2 : Sequence>(
  _ sequence1: Sequence1, _ sequence2: Sequence2
) -> Zip2Sequence<Sequence1, Sequence2> {
  return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2)

So once again, I’m trying to figure out how I would fold this rationally. I’m not a huge fan of the parameter list on a single line like this, especially when there are both external (_) and internal labels involved, generic parameter types, and a complex return type.

I was thinking of something more like this:

public func zip<Sequence1, Sequence2> (
    _ sequence1: Sequence1,
    _ sequence2: Sequence2
    -> Zip2Sequence<Sequence1, Sequence2>
    where  Sequence1: Sequence, Sequence2: Sequence
    return Zip2Sequence(_sequence1: sequence1, _sequence2: sequence2)

This update moves each parameter to its own line and splits off both the return type and the constraint clause. What do you think? How would you personally fold it? Let me know and thanks.

How do you beautify guard-else conditions?

This looks horrible to me.

Screen Shot 2016-08-23 at 11.03.47 AM

This looks wrong too:

Screen Shot 2016-08-23 at 11.06.56 AM

And so does this:

Screen Shot 2016-08-23 at 11.07.50 AM

And this:

Screen Shot 2016-08-23 at 11.08.25 AM

And while we’re at it  these two too, both of which require hand-indenting while fighting Xcode:

Screen Shot 2016-08-23 at 11.17.53 AM

Screen Shot 2016-08-23 at 11.17.59 AM

This is among the least bad:

Screen Shot 2016-08-23 at 11.08.59 AM

What would you do to fix it?

Patrick Perini suggests:

Greg Titus thought using a simpler clause and a Never-returning function might be better. Here’s some code where I incorporated his feedback:

Dear Erica: How do I mimic Objective-C’s delegate inheritance pattern?

Kyle: “Is it possible to have class Foo: Bar where Foo has a delegate of type protocol FooDelegate: BarDelegate where Bar also has a delegate declared as type BarDelegate?  In my case i am subclassing scrollview and want to declare delegate as my own type that conforms to UIScrollViewDelegate? I get the error that a property delegate with type FooDelegate? cannot override a property with type UIScrollviewDelegate?”

If I’m understanding, you want to be able to create delegation where the same property (delegate) can be assigned to ever more specialized protocols when subclassing. So, for example, you might have a base class like UIScrollView whose delegate is UIScrollViewDelegate, and a subclass like UITableView whose delegate is UITableViewDelegate. Right?

In Swift, you must ensure the child protocol conforms to the parent protocol. I do not believe is the case with the scroll and table view delegates in Objective C. Start with a core delegate protocol like this.

public protocol DelegateProtocol: class {
    func showMyType() -> Void

It’s an empty placeholder for all delegation protocols. You don’t need the showMyType requirement here. I’m just putting it in for demonstration, so you can check where the required member is implemented. If you want to use weak delegation, you must declare class, as in this example.

To demonstrate how this works, here are a core delegate protocol and a derived one:

public protocol CoreTypeDelegate: DelegateProtocol {}
extension CoreTypeDelegate {
    public func showMyType() { print ("This is a Core Type Delegate (required)") }
    public func shared() { print ("Shared at Core level (extension)") }

public protocol DerivedTypeDelegate: CoreTypeDelegate {}
extension DerivedTypeDelegate {
    public func showMyType() { print ("This is a Derived Type Delegate (required)") }
    public func shared() { print ("Override at Derived level (extension)") }
    public func exclusive() { print ("Implemented only at Derived level (extension)") }

// Implement one of each
class ACoreDelegate: CoreTypeDelegate {} // like UIScrollViewDelegate
class ADerivedDelegate: ACoreDelegate, DerivedTypeDelegate {} // like UITableViewDelegate

print("-- Core delegate")
let myCoreDelegate = ACoreDelegate()
myCoreDelegate.shared() // core version
myCoreDelegate.showMyType() // core version

print("-- Derived delegate")
let myDerivedDelegate = ADerivedDelegate()
myDerivedDelegate.shared() // derived override
myDerivedDelegate.showMyType() // derived version
myDerivedDelegate.exclusive() // only in derived

These three methods differentiate how required members, extension-only members, and exclusive-members are accessed when instances are used in different roles.

Next, here’s a basic protocol for classes that use delegates:

public protocol Delegatable {
    associatedtype DelegateType: DelegateProtocol
    var delegate: DelegateType? { get set }

This protocol consists of a conforming type declaration, and a delegate property. This indirection allows you to store instances of arbitrary types, so you can use the same delegate property for both a base class and its more specialized children.

To see this in action, you need delegatable types . Here’s a base class, similar to the role that scroll views play. (Warning: weak delegation will crash playgrounds. If you’d rather use a playground, omit weak in the property implementation.)

// Like UIScrollView
public class BaseClass<Delegate: CoreTypeDelegate>: Delegatable {
    public typealias DelegateType = Delegate
    public weak var delegate: DelegateType? = nil
    public func baseFunc() { print("implemented in base class") }

Now you can create an instance, specifying a base class for delegation:

var myBaseInstance = BaseClass<ACoreDelegate>()
myBaseInstance.delegate = myCoreDelegate // ok
print("-- Should use core implementations")

The derived delegate class inherits from the base delegate class. You can substitute it in, but the instance will still use core implementations.

print("-- Conformance by derived delegate type")
print("is CoreTypeDelegate", myDerivedDelegate is CoreTypeDelegate) // true
print("is DerivedTypeDelegate", myDerivedDelegate is DerivedTypeDelegate) // true
print("is ACoreDelegate", myDerivedDelegate is ACoreDelegate) // true
print("is ADerivedDelegate", myDerivedDelegate is ADerivedDelegate) // true

print("-- Will still use core implementations, because it's typed to CoreTypeDelegate")
myBaseInstance.delegate = myDerivedDelegate // ok

print("-- Casting delegate, only required implementation does not override")
    let derived = myBaseInstance.delegate as? DerivedTypeDelegate  else {
        fatalError("Cannot cast derived delegate to DerivedTypeDelegate")
derived.showMyType() // still uses core showme
derived.shared() // uses derived shared
derived.exclusive() // not available in core

Subclassing the base class and creating instances with the derived delegate protocol enables you to use the delegate property with a more specialized feature set.

// Like UITableView
public class DerivedClass<Delegate: DerivedTypeDelegate>: BaseClass {
    public func derivedFunc() { print("implemented in derived class") }
var myDerivedInstance = DerivedClass<ADerivedDelegate>()
// myDerivedInstance.delegate = myCoreDelegate // no, does not allow, cannot assign value of type 'ACoreDelegate' to type 'ADerivedDelegate?'
myDerivedInstance.delegate = myDerivedDelegate // yes

print("-- Should use native implementations for all")
myDerivedInstance.delegate?.showMyType() // yes!

As always, I’ve probably messed up some things along the way, so if you have better solutions or you find an issue in this example, please let me know and I’ll fix. Thanks!

Stateful loops and sequences

An intriguing request came up on Swift-Ev a day or so ago:

I’ve come across a situation a number of times where I write code that has to try something one or more times using a `repeat…while` loop and the condition relies upon variables that should be declared within the scope of the loop.

repeat {
    let success = doSomething()
} while !success

What caught my eye about this request is the need for state that’s visible both within scope and in the control structure without being declared in the outer scope.

This mechanism already exists in Swift. Meet Swift’s new sequence functions. Swift offers two varieties. Both offer ways to establish state confined to the loop scope.

public func sequence<T>(first: T, next: (T) -> T?) -> UnfoldSequence<T, (T?, Bool)>

public func sequence<T, State>(state: State, next: (inout State) -> T?) -> UnfoldSequence<T, State>

The difference between the two is this: The simpler first function produces a sequence of the same type as its state. The second variation (which actually used to implement the first one) differentiates the state type from the output type, so you could generate integers and operate on strings if you wanted to.

If you think about it, a repeat-while loop really is just a sequence written in a different form. Here’s a simple example that counts by 5.

var i = 0
repeat {
    print(i) // some loop body
    i = i + 5
} while i <= 100

You can rewrite this to incorporate the i-variable state into the control structure like so

for i in sequence(first: 0, next: { $0 + 5 }) {
    print (i) // some loop body
    if i >= 100 { break } 

Or you can be slightly more daring and move all behavior and state into the next closure:

for _ in sequence(first: 0, next: {
    print($0) // some loop body
    let value = $0 + 5
    return value <= 100 ? value : nil
}) {}

There are three big things to note about this modification:

  1. The for-loop doesn’t need a variable. It’s only being used to run the sequence.
  2. The loop body is empty. It’s just there to complete the syntax for for in. You could just as easily perform Array(sequence) but that would require memory allocation, which is wasteful.
  3. The sequence must terminate by returning nil. This means the closure’s return type is T?, where T is the type of the first argument. This example returns value,  but it could just as easily return any number (like 0 or 1 or 42 or Int()) because that value will never be used in any meaningful way here. It’s just checking for false/nil.

If you’re going to treat Boolean conditions as optionals, it helps to have a quick way to convert a Boolean to an optional equivalent. This is overkill but it gets the job done.

extension Bool { var opt: Bool? { return self ? self : nil } }

Alternatively, you can build a function that operates on Boolean tests so you don’t need to convert Booleans to optionals when building weird for-loop sequences.

The perform function that follows creates a stateful repeat-while loop, which is more or less what I believe the writer was aiming for. It uses a Boolean test, hides the use of sequence(state:next:), and allows a trailing closure for the body of the loop.

func perform<T>(
    with state: T,
    while test: (T) -> Bool,
    repeat body: (inout T) -> Void) -> T {
    var updatedState: T = state
    let boolSequence = sequence(state: state, next: {
        (state: inout T) -> Bool? in
        updatedState = state
        return test(updatedState) ? true : nil
    for _ in boolSequence {}
    return updatedState

// The following example joins the words into a single space-delimited string.
let joinedWords = perform(
    with: ["Lorem", "ipsum", "dolor", "sit", "amet", "consectetur", "adipiscing", "elit"],
    while: { $0.count > 1 })
    (state: inout [String]) in
    guard state.count >= 2 else { return }
    let (last, butLast) = (state.removeLast(), state.removeLast())
    let joinedLast = butLast + " " + last


The key bit to notice is that the initial word array isn’t stored anywhere external to the loop but can be operated upon within the loop body. I believe this is exactly what the original writer asked for when he wrote, “code that has to try something one or more times using a `repeat…while` loop and the condition relies upon variables that should be declared within the scope of the loop”