<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Sergey Gavrilyuk on Medium]]></title>
        <description><![CDATA[Stories by Sergey Gavrilyuk on Medium]]></description>
        <link>https://medium.com/@sergey.gavrilyuk?source=rss-c1ed19ef6042------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*aSLqtGEb9C6Pzqnj.</url>
            <title>Stories by Sergey Gavrilyuk on Medium</title>
            <link>https://medium.com/@sergey.gavrilyuk?source=rss-c1ed19ef6042------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 09:46:16 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@sergey.gavrilyuk/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Dynamic Encodable with type erasure]]></title>
            <link>https://medium.com/@sergey.gavrilyuk/dynamic-encodable-with-type-erasure-1875722b3171?source=rss-c1ed19ef6042------2</link>
            <guid isPermaLink="false">https://medium.com/p/1875722b3171</guid>
            <category><![CDATA[ios]]></category>
            <category><![CDATA[ios-app-development]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[codable]]></category>
            <dc:creator><![CDATA[Sergey Gavrilyuk]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 21:29:54 GMT</pubDate>
            <atom:updated>2018-02-27T21:29:54.534Z</atom:updated>
            <content:encoded><![CDATA[<p>Swift 4 brought us new Codable APIs aiming to simplify serializing and deserializing data models into various formats, most popular of which is json. Swift 4 compiler has special support for these APIs in form of code autogeneration. This post is about a small yet annoying problem that you might face while adopting Encodable protocol for <em>dynamic</em> <em>structure</em> models.</p><h4>The problem</h4><p>Suppose we want to serialize some data, which can be structured in a dynamic way. Let me explain what I mean by that. We will be serializing model Packet which contains some statically defined properties, like date, as well as one dynamically defined property called payload. The reason why I call it dynamic is that several different types should be able to fit into that payload. The only common thing between those types is that they should be Encodable as well.</p><pre>struct SomeDataModel: Encodable {}<br>struct SomeOtherDataModel: Encodable {}</pre><pre>struct Packet: Encodable {<br>  var date: Date<br>  var payload: Encodable<br>}</pre><p>If you try to put that into playground it won’t compile</p><blockquote>cannot automatically synthesize ‘Encodable’ because ‘Encodable’ does not conform to ‘Encodable’</blockquote><p>That reads odd, doesn’t it? Well, let’s try to figure out what’s wrong. Encodable requires to have only one method</p><pre>public func encode(to encoder: Encoder) throws</pre><p>so maybe we can implement that method ourselves? For that we will also have to define CodingKeys enum. Let’s see</p><pre>struct Packet: Encodable {<br>  var date: Date<br>  var payload: Encodable</pre><pre>  enum CodingKeys: String, CodingKey {<br>    case date, payload<br>  }</pre><pre>  public func encode(to encoder: Encoder) throws {<br>    var container = encoder.container(keyedBy: CodingKeys.self)<br>    try container.encode(date, forKey: .date)<br>    try container.encode(payload, forKey: .payload)<br>  }<br>}</pre><p>That doesn’t compile either:</p><blockquote>error: ambiguous reference to member ‘encode(_:forKey:)’</blockquote><p>and it only complains about the line where we try to encode payload. And the reason why it complains is that encode for custom types is actually generic method parameterized with that custom type. It’s static, meaning that it requires to know exact type of what we’re trying to encode before invoking encode(forKey:). Since we don’t have type at this point, we only know that this type conforms to Encodable. To me — that should be enough, after all, that’s all encode(forKey:) cares about. But it’s just the way encodable APIs were designed.</p><p>There are ways to make Packet conform to Encodable with dynamic payload. Most straightforward (and I would argue — the intended) way would be to make Packet generic:</p><pre>struct Packet&lt;T: Encodable&gt;: Encodable {<br>  var date: Date<br>  var payload: T<br>}</pre><p>and it works! Even without explicit Encodable implementation — compiler can autogenerate all that boilerplate for us.</p><p>There is downside to this approach though. Since Packet is now generic — you’d have to make every method taking Packet as a parameter to be generic over payload type. That may require a lot of changes in existing code, not to mention, also leaks of implementation details. And if you happen to have method <em>returning</em> Packet — you’re going to have even more headache.</p><h4>Good old Type Erasure</h4><p>There is a way to simplify Packet using the <a href="http://chris.eidhof.nl/post/type-erasers-in-swift/">Type Erasure pattern</a>. Consider we have helping internal type</p><pre>struct AnyEncodable: Encodable {<br>  var _encodeFunc: (Encoder) throws -&gt; Void<br>  <br>  init(_ encodable: Encodable) {<br>    func _encode(to encoder: Encoder) throws {  <br>      try encodable.encode(to: encoder)<br>    }<br>    self._encodeFunc = _encode<br>  }</pre><pre>  func encode(to encoder: Encoder) throws {<br>    try _encodeFunc(encoder)<br>  }<br>}</pre><p>As you can see, this is a classic example of type erasure. It can turn any dynamic type conforming to Encodable into statically known type (since AnyEncodable is a struct) that also conforms to Encodable. We can use AnyEncodable as substitute for Encodable:</p><pre>struct Packet: Encodable {<br>  var date: Date<br>  var payload: AnyEncodable<br>}</pre><p>Compiler is perfectly fine with such definition: AnyEncodable is a statically known type (it’s a struct after all) and can happily autogenerate all the code required for Encodable for us. With small handy addition to our Packet type:</p><pre>init(date: Date, payload: Encodable) {<br>  self.date = date<br>  self.payload = AnyEncodable(payload)<br>}</pre><p>we can use Packet in the same way we wanted to use it from the beginning when trying to annotate payload as Encodable.</p><p>As a conclusion I wanted to emphasize again how type erasure isn’t the only way to approach the problem but how it allows us to have minimum integration changes and keep APIs simple.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1875722b3171" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type safe animations in swift]]></title>
            <link>https://medium.com/ios-os-x-development/type-safe-animations-in-swift-53b15f27fa2c?source=rss-c1ed19ef6042------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b15f27fa2c</guid>
            <category><![CDATA[animation]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sergey Gavrilyuk]]></dc:creator>
            <pubDate>Tue, 12 Sep 2017 13:11:24 GMT</pubDate>
            <atom:updated>2017-09-13T14:09:20.315Z</atom:updated>
            <content:encoded><![CDATA[<p>Animations are at the core of UX anticipated on any modern UI platform, and iOS is (and has been from the very beginning) one the main drivers of this experience. Pioneering with animation APIs back in the days using existing tech like c++ and Objective-C, however, lead to many outdated APIs at this point. Since swift language inception there have been many attempts to transition existing animation APIs (written in Objective-C and heavily exploiting objective-C runtime) into swift syntax. Resulting APIs, however, are still far from ideal.</p><p>My attempt to look at this problem from different angle and trying to design general animation APIs as with Swift-first approach resulted in a framework called <a href="https://github.com/gavrix/AnyAnimation">AnyAnimation</a>. It’s a set of general definitions and basic components’ implementations. Core is written in pure swift which makes it potentially cross-platform (although not tested yet) with integration for iOS implemented as a reference.</p><p>Let’s take a look at what AnyAnimation is.</p><h3>Animation basics</h3><p>First we need to define our terminology. What is animation after all? There are probably several ways to define animation, but the simplest one I like would be</p><blockquote>It’s a smooth transition between states.</blockquote><p>This definition imply that there is state or rather set of states, there is smooth transition between them, and something performs that transition. These are essential components or our animation APIs. Let’s take a closer look at each of them</p><h4>State</h4><p>UI state in particular. It’s geometry, any properties of UI component that get translated onto the screen through rendering process. State can be represented as scalar values (Floats, Ints) or as any other derivative or complex data structure. The only requirement for state is — we need to be able to calculate intermediate values between edge states: we need to be able to perform interpolation. This requirement can be expressed as</p><pre>public protocol Interpolatable {<br>    func interpolate(to: Self, by: Float) -&gt; Self<br>}</pre><p>For scalar states we can define a default linear interpolation:</p><pre>public protocol ScalarInterpolatable {<br>    static func *(lhs: Self, rhs: Float) -&gt; Self<br>    static func +(lhs: Self, rhs: Self) -&gt; Self<br>}<br><br>extension Interpolatable where Self: ScalarInterpolatable {<br>    public func interpolate(to finalState: Self, by percent: Float) -&gt; Self {<br>        return self * (1 - percent) + finalState * percent<br>    }<br>}</pre><p>Now, state itself needs to be expressed somehow so that running mutation can mutate it from one side, and UI reflecting it’s changes from the other. That can be done using an observable property patterns:</p><pre>public class AnimatableProperty&lt;T: Interpolatable&gt; {<br>  internal(set) public var value: T<br>  private let didChange: (T) -&gt; Void<br>  public init(_ value: T, didChange: @escaping (T) -&gt; Void) {<br>      self.value = value<br>      self.didChange = didChange<br>  }<br>}</pre><h4>Animation</h4><p>Animation object controls the transition flow. There are different kinds of transitions, likewise we can define different kinds of animations. When it comes to transitioning from start state to the finish given animation parameters — timing function and duration — animation interpolates intermediate state based on elapsed time. But there may be another kind of animation — like a group of other animations. This kind of animation doesn’t have any state defined and coordinates transitioning of internal sub-animations it contains. What any animation should be capable of, though, is performing a transition tick. We can define Animation as protocol:</p><pre>protocol Animation {<br> func tick(at time: RelativeTimeInterval)<br>  ...<br>}</pre><p>Here, RelativeTimeInterval is a special type used for convenience to give a context of nature. Really, it’s just a wrapper for TimeIntervalthat guarantees that it’s going to be in the range [0, 1]. Thus, animation should perform transition from beginning to end by being able to transition to time with this relative range.</p><p>Since we use relative time in this APIs, Animator needs to know how to calculate relative state of this particular animation form current time at every tick — which is obviously absolute time. To be able to do that every animation needs to tell it’s duration. So that final form of Animation requirements would be</p><pre>public protocol Animation {<br>    func tick(at time: RelativeTimeInterval)<br>    var duration: TimeInterval { get }<br>}</pre><p>AnyAnimation comes with several basic Animation implementations. Let’s first take a look at important primitive ones that allows to synchronize several other animations: <strong>group</strong> and <strong>sequence</strong>. These APIs are similar to the ones used in SpriteKit:</p><ul><li>AnimationSequencemanages group of animations to run in sequence one after another.</li><li>PropertyAnimation manages group of animations to run simultaneously and start at the same time.</li></ul><p>durationproperty of these special animations is calculated based on containing animations: for <strong>sequence</strong> it’s a sum of containing animation’s durations and for <strong>group</strong> — it’s a longest containing animation’s duration.</p><p>PropertyAnimation is an abstract animation (defined as protocol extending Animation) that defines shape of animation that can actually do something useful — transition some property between states:</p><pre>public protocol PropertyAnimation: Animation {<br>  associatedtype T: Interpolatable	<br>  var animatableProperty: AnimatableProperty&lt;T&gt; { get }<br>  func interpolatedValue(at state: RelativeTimeInterval) -&gt; T<br>}</pre><p>As you can see, this shape requires specific property animation to be parametrized by type of the state — be it CGFloat or CGPoint or even CGPath. interpolatedValue(at:) narrows down the context of what’s going here — really every tick we only need to calculate that value and assign to underlying property. And that is true for any implementation of such animation, which can be expressed as:</p><pre>extension PropertyAnimation {    <br> public func tick(at time: RelativeTimeInterval) {<br>   animatableProperty.value = interpolatedValue(at: time)<br> }<br>}</pre><p>There are 2 specific implementation for property animations in AnyAnimationframework: BasicAnimation and KeyPointsAnimation (which are similar to APIs defined in QuartzCore). You are welcome to explore their implementations in details.</p><h4>Animator</h4><p>Animation as a smooth transition is a matter of timing. As time goes by we need to tell all animations that are currently being run to update to current time — this is a job for Animator. In most animation APIs available on iOS this entity is abstracted away and hidden. Thus, we only add animations to CALayer and have no idea <em>who</em> calculates interpolated values between animation frames, we only see that those values change on presentationLayer. Or, when we add SKAction’s to SKNode we don&#39;t know <em>who</em> calculates and applies interpolated values to owning node.</p><p>In AnyAnimation APIs Animator is responsible for calling tick(at:) at proper time with proper values. Obviously, there needs to be a way to kick off new animation:</p><pre>public protocol Animator {<br>  func run(animation: Animation)<br>}</pre><p>AnyAnimation comes with several Animator implementations using underlying timing APIs available on iOS:</p><ul><li>SpriteKit (SKAnimator) — leveraging SKAction.customAction</li><li>DisplayLink (DisplayLinkAnimator) — leveraging CADisplayLink</li><li>CALayer (LayerAnimator) — leveraging CALayer with custom property (time) animation</li></ul><p>AnyAnimation also provides simple implementation for ManualAnimatorwhich can point running animation to a specific point in time manually, through user input for example. It could be used as a debugging tool to test out particular (and rather complex) animations composition driven by input from UI.</p><h3>Putting it all together</h3><p>AnyAnimation comes with an example app showcasing how these APIs could be used. Here’s a quick sample code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c968477469cb7245019c109cb7460277/href">https://medium.com/media/c968477469cb7245019c109cb7460277/href</a></iframe><h3>Conclusion</h3><p>My goal was to add more type-safety to animation APIs compared with existing animation APIs and the result looks promising. You are welcome to explore <a href="https://github.com/gavrix/AnyAnimation">AnyAnimation</a>repo and any comments and suggestions on how to improve these API are very welcome!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b15f27fa2c" width="1" height="1" alt=""><hr><p><a href="https://medium.com/ios-os-x-development/type-safe-animations-in-swift-53b15f27fa2c">Type safe animations in swift</a> was originally published in <a href="https://medium.com/ios-os-x-development">iOS App Development</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Type Injection in swift]]></title>
            <link>https://medium.com/shopify-mobile/type-injection-in-swift-c576b53c5b4?source=rss-c1ed19ef6042------2</link>
            <guid isPermaLink="false">https://medium.com/p/c576b53c5b4</guid>
            <category><![CDATA[swift]]></category>
            <dc:creator><![CDATA[Sergey Gavrilyuk]]></dc:creator>
            <pubDate>Wed, 26 Jul 2017 21:50:30 GMT</pubDate>
            <atom:updated>2017-07-26T21:50:30.546Z</atom:updated>
            <content:encoded><![CDATA[<p>A friend of mine who is new swift (but who has overwhelming experience in android using both java and kotlin) approached me recently with a question/concern: why aren’t there abstract classes in swift? His comment on justifying the need of abstract class was this: I want to be able to flash out most of the functionality in my class but there’s some minor thing that I want to leave abstract — and defined by subclasses. Here’s what I told him.</p><p>Abstract classes used to be one of the major advantages of modern OOP languages like c++ and java. It makes it possible distribute functionality implementations between classes in inheritance hierarchy. I remember mimicking that design in Objective-C by providing actual method implementation with contents like</p><pre>- (void)abstractMethod {<br> @throw [NSException exceptionWithName:NSInvalidArgumentException <br>                                reason:[NSString stringWithFormat:@”%s must be overridden in a subclass/category”, __PRETTY_FUNCTION__] <br>                              userInfo:nil]<br>}</pre><p>since Objective-C doesn’t have nice abstract method support.<br>However, this also encourages developers to introduce more levels in inheritance hierarchy, which (history proves) doesn’t scale and introduces unwanted strong coupling.</p><h4>Compose all the things!</h4><p>New type-oriented languages, like swift, encourages developers to leverage composition more in favour of inheritance. In my friend’s example he had a base StepViewController that did all the heavy work but had some definitions abstracted away like this StepViewController</p><pre>// this is abstract method<br>open func render() -&gt; [TableSection] {<br> return [] // <br>}</pre><p>and there was another SignUpViewController that implemented that one particular method:</p><pre>override func render() -&gt; [TableSection] {<br>   return [<br>     TableSection(rows: [<br>        firstNameCell(),<br>        lastNameCell(),<br>        businessCell(),<br>        emailCell(),<br>        passwordCell()<br>     ])<br>   ]<br>}</pre><p>This could be re-factored in a way so it doesn’t use inheritance for this kind of abstraction. We could leverage dependency injection by moving this render() function into a dependency:</p><pre>protocol Renderer {<br> func render() -&gt; [TableSection]<br>}</pre><p>and then make StepViewController use it as a type of a property:</p><pre>class StepViewController {<br> …<br> var renderer: Renderer</pre><pre> private func render() -&gt; [TableSection] {<br>   return renderer.render()<br> }<br>}</pre><p>Notice how I changed declaration of render() function in StepViewController — it’s now private as it’s not exposed externally anymore and only needed to be used internally.<br>There’s one thing missing though: injection. We need a way to provide dependency at StepViewController creation — through constructor. It’s going to be challenging to make clean with subclasses of UIViewController though. First, we would need to disable all UIViewController’s provided constructors:</p><pre><a href="http://twitter.com/available">@available</a>(iOS, unavailable)<br>init() { fatalError() }</pre><pre><a href="http://twitter.com/available">@available</a>(iOS, unavailable)<br>override init(nibName nibNameOrNil: String?, bundle nibBundleOrNil: Bundle?) { fatalError() }</pre><pre><a href="http://twitter.com/available">@available</a>(iOS, unavailable)<br>required init?(coder aDecoder: NSCoder) { fatalError() }</pre><p>And then we’ll provide required constructor taking dependency:</p><pre>required init(dependency: Renderer) {<br> self.renderer = dependency<br> super.init(nibName: nil, bundle: nil)<br>}</pre><p>This seems to be enough: it’s now impossible to create and instance of StepViewController without a renderer dependency. Going back to my friends example, he wanted to define abstraction details in subtype — so he can use that subtype as elsewhere. Ok, here it is:</p><pre>class SignUpViewController: StepViewController {<br> convenience init() {<br>   super.init(dependency: SignUpRenderer())<br> }<br>}</pre><p>That won’t work though, because we already disabled that kind of `init`. The solution would be using static function instead of constructor, like:</p><pre>static func instantiate() -&gt; SignUpViewController {<br> return SignUpViewController(dependency: SignUpRenderer())<br>}</pre><p>This introduces a couple of things: <br>1. This kind of construction if type-bound, e.g. non-virtual (and if you do want to make it virtual you’d have to add static instantiate to base class with empty implementation, kind of what we wanted to avoid)<br>2. It’s possible to create instance of SignUpViewController using constructor with dependency that might not be what SignUpViewController wants it to be. What if we wanted to lock type of dependency to the type of it’s user?</p><h4>Type injection</h4><p>When we want to lock type of dependency to the type of it’s user — we need to be looking at type parameterization, e.g. generics. Turns out it solves all my concerns expressed earlier.<br>Let’s make StepViewController generic first:</p><pre>class StepViewController&lt;RendererType: Renderer&gt;: UIViewController {<br> var renderer: RendererType<br> init() {<br>   renderer = RendererType()<br> }<br>}</pre><p>Then, making SignUpViewController to lock into particular Renderer is trivial:</p><pre>typealias SignupViewController = StepViewController&lt;StepHeaderRenderer&gt;</pre><p>Note, that it’s effectively injected type and this type can be accessible anywhere in code of base StepViewController — including all it’s designated constructors. We can still have dependency instance injection by using all above techniques with disabling existing constructors and providing our own. However, now we could guarantee that dependency type is a designated one:</p><pre>extension StepViewController<br> init(depedency: RendererType) {<br>   self.init()<br>   self.renderer = depedency<br> }<br>}<br></pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c576b53c5b4" width="1" height="1" alt=""><hr><p><a href="https://medium.com/shopify-mobile/type-injection-in-swift-c576b53c5b4">Type Injection in swift</a> was originally published in <a href="https://medium.com/shopify-mobile">Shopify Mobile</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Swift Enums as namespace]]></title>
            <link>https://medium.com/swift-programming/swift-enums-as-namespace-7df63a17f36f?source=rss-c1ed19ef6042------2</link>
            <guid isPermaLink="false">https://medium.com/p/7df63a17f36f</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[swift]]></category>
            <category><![CDATA[ios]]></category>
            <dc:creator><![CDATA[Sergey Gavrilyuk]]></dc:creator>
            <pubDate>Mon, 18 Apr 2016 19:54:37 GMT</pubDate>
            <atom:updated>2016-05-02T13:41:42.518Z</atom:updated>
            <content:encoded><![CDATA[<p>While moving from objective-c to swift many developers have found swift’s enums to be much powerful tool than it used to be before. It’s algebraic nature (data exclusivity) and excellent native compiler support (powered by pattern match) made it so much easier to do a lot of routine stuff. Also, people noticed that it’s now easier to leverage static type checks that come along with these enums to bring more API safety and consistency. That all is great, until we start abusing this tool.</p><p>I came across <a href="https://github.com/Moya/Moya/blob/master/docs/Examples.md">this approach</a> to define RESTful services endpoints using enum, first employed by <a href="https://github.com/Moya/Moya">Moya framework</a>. The idea of wrapping list of endpoints in enum looked fresh and tempting to try. It provided the way of creating clean API, simple abstraction:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c883bbd54424ef025b3a25281b978e98/href">https://medium.com/media/c883bbd54424ef025b3a25281b978e98/href</a></iframe><p>By making <em>makeCall </em>method to accept arguments of enum type we could limit the set of endpoints it supports. Furthermore, enum type would provide code completion after typing “.” which would be very handy. Also worth mentioning, any additional endpoint-specific data would be carefully handed but that specific case, no untyped parameters list.</p><p>I didn’t like Moya’s implementation though. The idea is simple, but they ended up with massive implementation, even adding data mocking support into their core. I think that feature would be nice-to-have, through some sort of plugin or extension, but not in the core. So I took the idea and implemented my own HTTPEndPoints micro-framework.</p><p>First I defined enum with endpoints names and custom data, then I provided extension where I defined all the specifics of those endpoints: HTTP method, encoding, data and so on.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ba1f2fc79321106a0ced62b370b3af4/href">https://medium.com/media/7ba1f2fc79321106a0ced62b370b3af4/href</a></iframe><p>It was fine at the beginning, but while developing my app, I kept adding new endpoints. Until I got around 20+ endpoints and the code became messy.</p><p>A couple of days ago stumbled upon <a href="http://kostiakoval.github.io/posts/swift-enums-the-not-so-good-parts">this post</a> where author is talking about using enum in other very similar use case. He’s arguing against enums in cases data is scattered across different places. He says that sometimes it is still better to use old-school approaches with protocols defining module functionality and a set of concrete module implementations.</p><h3>Better enums</h3><p>Let’s reflect on why we get something wrong here. The main problem with defining our endpoints as single enum is that fulfilling actual implementation requires several methods, and information related to a particular endpoint (which one enum’s case) is now distributed across several methods (or variable getters). We can solve that by using technique described in <a href="http://cjwirth.com/2016/03/14/easier-enums/">this post:</a> wrap information related to each endpoint into private struct or even tuple. That would solve the problem of data being scattered and would definitely simplify updating our enum while refactoring.</p><h3>Enum as namespace</h3><p>When think about this further I asked myself: this private struct or tuple that is going to wrap all information related to particular enum’s case really fulfills my <em>HTTPEndpoint</em> interface, why not making that private struct to conform the that interface and not my initial enum? By this we effectively come to the idea of using protocol and multiple implementations as in <a href="http://kostiakoval.github.io/posts/swift-enums-the-not-so-good-parts">this post</a> I mentioned. But we could still use enum to construct those implementations. In this case enum work just like a namespace. Consider this example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/45a954df2504e799a171bc87dc1d30d8/href">https://medium.com/media/45a954df2504e799a171bc87dc1d30d8/href</a></iframe><p>I used a little trick here, I made my enum holding implementations of the protocol to be convertible to that protocol. I still have to make separate implementations for my protocol <em>LoginProvider</em> in separate classes, but I can alias them with enum cases, and that <em>convertibility</em> is what bridges enum approach and protocol-implementation approach. I have clean functionality implementation and neat namespace-like grouping of those implementations so I can restrict APIs to accept only implementations from that group and enum’s autocompletion.</p><p>As to my <em>HTTPEndpoint</em> micro-framework that I used in one of my apps, I decided to construct a small DSL:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/588bca2b3536026963c175884e912501/href">https://medium.com/media/588bca2b3536026963c175884e912501/href</a></iframe><p>and with that I can add the following extension to my <em>Endpoints</em> enum:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87c205995d5e9190e46b57cd09445730/href">https://medium.com/media/87c205995d5e9190e46b57cd09445730/href</a></iframe><p><strong>Update: </strong>some code have been update with typos fixed thanks to <a href="https://medium.com/u/1e812dd09c28">Lasha Efremidze</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7df63a17f36f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swift-programming/swift-enums-as-namespace-7df63a17f36f">Swift Enums as namespace</a> was originally published in <a href="https://medium.com/swift-programming">Swift Programming</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>