Archive for the ‘Challenge’ Category

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")
myBaseInstance.delegate?.showMyType()
myBaseInstance.delegate?.shared()

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
myBaseInstance.delegate?.showMyType()
myBaseInstance.delegate?.shared()

print("-- Casting delegate, only required implementation does not override")
guard
    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!
myDerivedInstance.delegate?.shared()
myDerivedInstance.delegate?.exclusive()

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
        body(&state)
        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
    state.append(joinedLast)
}.first!

debugPrint(joinedWords)

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!