Archive for the ‘Challenge’ Category

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”

Make it Swifter Challenge

Today’s challenge is courtesy of the Swift Users email list, posted by Adriano Ferreira. His starting point is here, where he was really looking to simplify chained calls. But making things Swifter isn’t always just about making chaining look better.

func selectionSort(_ array: [Int]) -> [Int] {

    guard array.count > 1, let minElement = array.min() else {
        return array

    let indexOfMinElement = array.index(of: minElement)!

    // All of this just to filter out the first smallest element and return the rest
    // Also tried ‘suffix(from:)' here, but couldn’t make it work properly
    let rest = array.enumerated()
                    .filter({ index, _ in index != indexOfMinElement })
                    .map({ _, element in element })

    return [minElement] + selectionSort(rest)

What can make this Swifter?

First, practicality. Even though any array of 0 or 1 elements is already sorted, I don’t think adding code to test for those conditions is practical. I think it’s better just to streamline and let the code run, even if the case of one element isn’t perfectly ideal.

Second, flow. I don’t like the idea of first finding the minimum and then finding its index. Enumeration allows these operations to be run in tandem.

Third, style. Enumeration should really return (index: Index, value: Element) tuples. It doesn’t. So I took this opportunity to extend Array to create the kind of tuples I’d rather work with. Because of that, my solution is more complex than it really needs to be (for a sorting function no one ever actually uses) because I’d rather use code that handles $0.value and $1.index than $0.1 and $1.0.

My redesigned code is here. Share yours!