Closure-Based State

DZone 's Guide to

Closure-Based State

· Mobile Zone ·
Free Resource

          ZONE:  Mobile
TLDR:   State implementation in Swift
ted.neward - Interoperability Happens 

A Closure-based State implementation in Swift.

Implementation: Swift

Implementing Closure-based State in Swift is not difficult; the languagesupports function literals as first-class citizens, and the compiler is intelligent enough to knowhow to “close over” variables referenced in the enclosing scope, so a simple implementation lookspretty straightforward:

let operation = ({ () -> ((Int) -> Int) in
    var state = 100
    let inner = { (adjust: Int) -> Int in
        state = state + adjust
        return state
    return inner

let result = operation(100)


Like other strongly-typed object-oriented langauges, Swift will have a bit trickier time doing thisfor object types, since the interface needs to be known by clients ahead of time. Swift does havethe concept of a protocol, which serves much like an interface does in C# or Java (or a pure-abstractclass does in C++), and when combined with the fact that Swift allows nested classes within the scopeof a function, it seems highly likely that Swift will allow the localized definition of a class thatimplements a protocol and (given the above) uses closed-over variables for state:

// This code will fail to compile!
protocol Interface {
    func Operation(adjust: Int) -> Int;
let maker = { () -> Interface in
    var state = 100
    class Implementation : Interface {
        func Operation(adjust: Int) -> Int {
            state = state + adjust
            return state

    return Implementation()

Unfortunately, Swift has explicitly forbidden this, with an error message that really couldn’t be anymore clear: “Class declaration cannot close over value ‘state’ defined in outer scope.” (This is asof Swift 2.2 at this writing.) Attempts to close over reference-type instances defined in the outerscope fail with the same error message, so it appears that Swift explicitly forbids a class-orientedimplementation of this pattern.

architecture, design patterns, factory, java, javascript, swift, xamarin

Published at DZone with permission of Ted Neward , DZone MVB. See the original article here.

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}