Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Closure-Based State

DZone's Guide to

Closure-Based State

· Mobile Zone
Free Resource

Download this comprehensive Mobile Testing Reference Guide to help prioritize which mobile devices and OSs to test against, brought to you in partnership with Sauce Labs.


          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)
print(result)

Objects

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.

 

Analysts agree that a mix of emulators/simulators and real devices are necessary to optimize your mobile app testing - learn more in this white paper, brought to you in partnership with Sauce Labs.

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

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 }}