Swift Struct All The Things

Should Swift Presenters Be Classes or Structs?

Swift structs aka Swift structures came into being and there was much excitement. Members of my own team back then were leaning heavily towards the idea of structs everywhere. As shared in Swift Protocols With Associated Types – PATs, “We were going to use structs and protocols wherever we could.”

Swift Struct All The Things

Should Struct All The Things?

The excitement is over, the dust has settled, and lessons have been learned. Now the question has been raised, should Presenters be classes or structs?

Stack Overflow Discussion and Unfortunate Answer Bias

Titled Why Choose Struct Over Class?, this Stack Overflow post’s chosen answer has been subtly framed in a way that reflects that initial excitement of leaning heavily towards creating Swift structs. It’s framed as if there is a contradiction between the WWDC 2015 talk Protocol Oriented Programming in Swift and Swift Programming Language documentation.

Based on what I and others can tell, there’s no contradiction. Also, the final line in the accepted answer is under scrutiny. Here’s the line under scrutiny:

Also, keep in mind that these concepts are always evolving and The Swift Programming Language documentation was written before the Protocol Oriented Programming talk was given.

As Dan Rosenstark rightfully pointed out:

Last line should say, “My personal advice is the opposite of the documentation:”… and then it’s a great answer!

That said, the content in the accepted answer copied from various sources is good and the post has had a lot of great interaction in it. This content and the Apple sources referenced clearly show when to use a class and when to use a struct.

Architecture

First, let’s get something out of the way right away. Are our Presenters really Presenters in our CARFAX app architecture? As shared in A Hungry Reflection on “How to Isolate Client-Server Interaction Logic in iOS Applications”, there’s often a debate as to whether we’re set up more for a Model-view-presenter (MVP) architecture, versus Model View ViewModel (MVVM) architecture, versus a Presentation Model architecture. This kind of discussion has gone on for over a decade. Regardless of where you land in the debate, the things that hold our display logic are known as Presenters. For the purposes of this blog post, let’s call them Presenters.

Presenters – Class or Struct?

Presenters contain display logic. There is one instance of them created and they are hooked up to the View Controller classes. Their purpose in life is to contain display logic that is unit testable and help keep the View Controllers from being too big.

Copying or comparing instances of the presenters doesn’t make sense. Presenters don’t fall anywhere near the “Examples of good candidates for structures” list in the section titled “Choosing Between Classes and Structures” of the Swift documentation’s Classes and Structures page. The same is true for the “Classes and Structures” section of The Official raywenderlich.com Swift Style Guide which is a favorite of many teams.

Conclusion

Structs are awesome to use when passing around simple value objects, whose properties are value types, and are meant to be compared and/or copied. To use structs in other situations is an understandable mistake. In hindsight, our own team tried to make some things structs that should have been classes from the beginning. We fell slightly into the Golden Hammer Anti-Pattern trap. Using a struct for a Presenter or other things like Presenters isn’t upholding the semantic differences between a Swift struct and a Swift class.

Update: Added reference to the “Classes and Structures” section of The Official raywenderlich.com Swift Style Guide

iOS Color War! Appearance Proxy vs UIButton Title Text Color

Now here’s a weird issue that appeared in iOS 10, I found myself saying one day. I was seeing an iOS button’s title change color as a I navigated from one scene to the next. It got worse. When I navigated back, the button’s title color stayed the wrong color. It was the same color as all the labels in the iOS app. What’s going on?

We dug in deeper and discovered something. There was a nasty appearance proxy color issue where the appearance proxy would change the color of the UIButton‘s title text color even though the code was explicitly setting the color. In fact, the appearance proxy would set it to be the same color as it has configured for all UILabel objects. The configuration code for labels was like this:

UILabel.appearance().textColor = labelTextColor()

Since a UIButton contains a UILabel, that might make sense. How does one fix this situation?

The answer to fixing it was discovered after thinking about what was read in this Stack Overflow post titled Appearance Proxy overridden when resetting text:

iOS applies appearance changes when a view enters a window, it doesn’t change the appearance of a view that’s already in a window.

It turns out the code to explicitly set the color on the UIButton was getting called before the view appeared on the screen aka viewWillAppear. Once the view appeared on the screen, the appearance proxy would set the button’s label’s text color aka button title color.

As a side note, this only seemed to happen when using setAttributedTitle on the button as opposed to calling setTitleColor and setTitle separately. Unfortunately, we wanted different parts of the text to be different sizes. So, using setAttributedTitle still seemed like the thing we should do.

Given all that knowledge, we called setNeedsLayout on the UIButton in viewWillAppear and viewWillDisappear That fixed everything up! The button no longer appeared to change color when switching between screens. Hurrah!

 

 

Adding Swift Initializers Through Extensions

While watching the Stack Views with Enums by objc.io, I learned an interesting little tidbit. You can add a convenience constructor aka convenience initializer by extending a class. The benefit of doing such is that you don’t have to subclass the class. In hindsight, the availability of that feature seems obvious. The Swift reference even has a section called “Initializers”. However, this ability may be news to others as well.

Similar to what they show at 7:45 in the video, one can write the following:

Next, you can call this new init like any other initializer:

I highly recommend you watch the entire Stack Views with Enums video. Enjoy!

RxSwift and Squishing the Pyramid of Doom

Say, you just learned RxSwift and all about subscribeNext. You have a series of Harry Potter related service calls to make and they affect each other. Let’s also say they all return the same type of Observable<Person>. So, you start to call these services one after another using subscribeNext.

The indention of calls is known as the Pyramid of Doom. This is a case of not using all of the power that RxSwift offers. If we inject flatMapLatest into the mix instead of all subscribeNext calls, we get the following:

Not only is the flatMapLatest approach easier to read, but one can see easily where the addDisposableTo(disposeBag) should be added at the end to manage the memory.

This concept is also covered in the RxSwift Tips document. Enjoy all that RxSwift has to offer!

Swizzle Swift Class Methods

While writing some test Swift code, I ran into a situation where I wanted the implementation of a class method swapped out with some fake code. Basically, I wanted to swap out SomeClass‘s saveSomeThings class method with a fake one.

Inspired by NSHipster’s Swift & the Objective-C Runtime article, I came up with some concise code that does what I want. Focusing on only what shows the concept, we have the following example SomeClass:

The saveSomeThings method implementation is what we want to swap out with some fake code for testing purposes. How, you might ask? First, ensure the method has the dynamic keyword as discussed in this Stack Overflow post. Next, we grab a handle to the class method like so:

Now we need something to swap it with. What if we had a method inside a SomeTestClass class like the following just for testing purposes?:

We can grab a handle to the method like so:

The actual call to swap the implementation between the saveSomeThings and forTesting_SaveSomeThings is done using method_exchangeImplementations like this:

The SomeTestClass prefixes the originalMethod and swizzledMethod because I am storing them as static members of the SomeTestClass.

Those are all the magical pieces of this puzzle! Besides being on github, here is a complete Swift playground example to see it all in context:

At CARFAX, I have been fortunate enough to work on such interesting challenges like the one above in Swift, Objective-C and Java based languages. Since CARFAX is a growing company with opportunities that open up from time to time, you might want to checkout the CARFAX Career link.

Regardless, I hope you found the above information interesting and useful. Enjoy!

RxSwift Moved Swiftly from 1.9 to 2.1

RxSwift 2.1.0 is out! Congrats to kzaher and all the members.

Since things moved fast over the winter holidays in RxSwift, you might see some changes that happened between 2.0.0-beta.4 and 2.0.0 that interest you if you haven’t switched yet. When moving from the latest RxSwift beta to 2.0.0, the 2.0.0-rc.0’s Deprecated section of the Change Log may answer some compilation issues you face.

Straightforward changes were needed for my work. For example, I needed to stick Observable in front of create. As covered in the Change Log:

Deprecates free functions in favor of Observable factory methods

An interesting one involves Variable:

Deprecates Variable implementing ObservableType in favor of asObservable()

Looking at GitHubSignup “UsingVanillaObservables > 1″ and “UsingDriver > 2″ in the RxExample code, I see the answer to my questions and so much more. There is an emphasis on using Driver as opposed to Variable objects. Although, a deep dive into Driver is a whole other topic.

In regards to 2.1, the changes from 2.0 to 2.1 are minimal and had no impact on my work.

Enjoy the new stuff!

Swift structs, closures and Memory Leaks

Using structs and registering closures with a framework? Did you know closures are reference types?

If your closure is registered with a class from a framework and the closure is closing over self then you have a strong reference cycle memory issue. For example, let’s say we have a struct which has an RxSwift class Variable<String> member called someVariable.

When you give the subscribeNext the closure, it will store that closure into the framework. In other words, it has a reference to the closure. If you are referring to self in that closure, you have a strong reference cycle. The struct has a Variable which has a closure that has a reference back to the struct.

Can we just make the self reference a weak reference? No. Not if it’s a struct.

If it’s a class, we can do the following:

Note that we are using class and [weak self] now. We also took away the mutating from before the function.

That solves the memory issue! Thanks goes to some helpful humans which include Darren and Marc Khadpe in this Stackoverflow post.

Update: For an example such as this, Carlos García rightfully pointed out that using [unowned self] would be better. It’s faster and more. Carlos pointed out this article: How Swift Implements Unowned and Weak References and a related Twitter thread.

If you are going to use unowned, you will want to know when your app can crash when using it.  “Weak, Strong, Unowned, Oh My!” – A Guide to References in Swift is a good guide for when to use weak, unowned, and the default strong references.

Swift Protocols With Associated Types – PATs

What first led me into understanding Protocols With Associated Types (PATs)? Answer: RxSwift. It’s an awesome FRP framework for Swift.

What led me to the protocol compilation error “..can only be used as a generic constraint” which looks like this?

1PAT with compiler error

(Source: Alexis Gallagher – Protocols with Associated Types – 1:24)

Answer: Applying BDD (Behavior-Driven Development) to our Protocol Oriented MVVM RxSwift empowered code and using dependency injection.

We were going to use structs and protocols wherever we could. However, we had to back off some. Thanks to Alexis Gallagher, it’s clear now why we ran into the same problem that he presented in his video presentation, Protocols with Associated Types and how they got that way (maybe). Here’s a problem example he shows:

2PAT single variable declaration

(Same source: 2:47)

This great presentation was part of the 2015 Functional Swift Conference. The Protocols with Associated Types, and How They Got That Way slides are available. However, I highly recommend listening to the whole presentation. Since it’s 56 minutes long, this blog post links to certain key parts of it with associated snapshot images just to give you a taste of what is in there.

From this presentation, there are some crucial key takeaways:

  • Can’t use dynamic dispatch with PATs
  • typealias can do two very different things
  • There are workarounds if you need to do dynamic dispatch

Can’t Use Dynamic Dispatch With PATs

The compilation error “..can only be used as a generic constraint” described above shows how PATs are unique and different from plain old Protocols. The following dives into the ramifications of this situation:

3No Dynamic dispatch

(Same source: 6:54)

PATs are their own thing. As Alexis G. says, call them PATs and recognize how they are different.

typealias Can Do Two Very Different Things

4typealias two different uses

(Same source: 11:39)

As specified in the Swift Language Reference on Declarations, you can use typealias to:

  • Create a name for a type. See the “Type Alias Declaration” section.
  • Require something that conforms to a PAT, to specify a type. See the “Protocol Associated Type Declaration” section

Slide 18 of his presentation has a good example of showing typealias being used in a PAT.

There Are Workarounds If You need to do Dynamic Dispatch

11HowToLovePATs

(Same source: 39:08)

Workarounds are:

  • Enums
  • Type Erasure

The future looks bright if they add Existentials to the language. There is a Stackoverflow post about the generic concept an Existential Type.

Summary

Until they add Existential Types to the Swift language, we should fully understand PATs and how to use other parts of the Swift language to accomplish what we want.

As an aside: If you got this far, you really may want to watch the whole presentation on youtube. This blog post was made to just catch some of the interesting bits for later referral. Enjoy!

RxSwift Driver – What is it?

Curiosity is a powerful thing. When I saw this RxSwift Driver being discussed on RxSwift Slack and read the helpful RxSwift GitHub issue “Need better explanation / examples for Driver” submitted by Florent Pillet, it seemed helpful to capture what I saw.

As Carlos García shared on the GitHub issue:

One should think of the following:

as the same as:

Krunoslav Zaher aka kzaher on the RxSwift slack community said that it is a combination of: “main thread + shared subscriptions + no errors.” He goes on to say that shareReplay(1) is a shared subscriptions example. Carlos adds there are several examples in RxExample.

kzaher sums it all up nicely by sharing:

Yeah, it’s just a tiny builder/dsl for Observables. I think this should help me and others a lot with ensuring you can safely bind values to UI.

Using Driver is optional, but it helps the compiler catch things and will help emphasize things that might have been missed. As kzaher put it:

..and warn me when I’ve forgot to handle unexpected errors, or binding from background thread or doing something I should have when dealing with UI applications.

You may want to keep an eye on the RxSwift documentation as it grows and develops over time. Specifically, this Units document. Driver sounds exciting and I look forward to trying it in-depth in the near future!

Jan 2, 2016 Update: The Units document has been updated and much more has been added to it. Good stuff!

RxSwift Glossary and Concepts

Do you speak RxSwift? Do you know the concepts, words and operators? Here is a snapshot summary of many of them.

Some of the RxSwift Concepts from Getting Started

An Observable is a definition of: 

  • “..how the sequence is generated..”
  • “..what parameters are used for element generation..”

Disposing

“..release all of the resources that were allocated to compute upcoming elements..”

Observable aka Sequence

  • One after another, the Observable sends a Next (element), Error, or a Completed
  • What stops them from coming? An Error, Completed or dispose the subscriptions.

Observer

Subscribes to Observables

Subject

(Source: Rx.playground)

Terse mode: “acts both as an Observer and as an Observable”

Full mode: “A Subject is a sort of bridge or proxy that is available in some implementations of ReactiveX that acts both as an observer and as an Observable. Because it is an observer, it can subscribe to one or more Observables, and because it is an Observable, it can pass through the items it observes by reemitting them, and it can also emit new items.”

Operators

There is a list sorted by functionality at https://github.com/ReactiveX/RxSwift/blob/master/Documentation/API.md#rxswift-supported-operators

Operator Types:

(Sources: Rx.playground and github docs)

  • Combination operators – startWithcombineLatestmergeswitchLatestzip; “Operators that work with multiple source Observables to create a single Observable”
  • Conditional and Boolean Operators – takeUntiltakeWhile – “Operators that evaluate one or more Observables or items emitted by Observables.”
  • Connectable Observable Operators – multicastreplay, replayAll, publish – “like an ordinary Observable yet only when its connect() is called does it emit”
  • Error Handling Operators- catchErrorretry – “Operators that help to recover from error notifications from an Observable.”
  • Filtering Observables – distinctUntilChanged, filtertake; “Operators that selectively emit items from a source Observable.”
  • Mathematical and Aggregate Operators – concat, reduce – “Operators that operate on the entire sequence of items emitted by an Observable”
  • Observable Utility Operators – doOn, subscribesubscribeNextsubscribeCompletedsubscribeError; “toolbox of useful Operators for working with Observables”
  • Transforming Observables – map / selectflatMapscan; “Operators that transform items that are emitted by an Observable”
  • Units – “purpose of Driver unit is to ensure the underlying observable sequence has the following properties”: It “can’t fail”, “main thread”, and more.

Schedulers

Schedulers are an abstraction away from what does work (queues / threads).

RxSwiftCommunity

By the way, the RxSwiftCommunity bears checking in on from time to time. Action is listed there and it comes up often in the RxSwift Slack community and at least once in Stack Overflow. Just like the adoption of RxSwift, I sense the community will grow over time.

Update: If one looks at the code commits done for the RxSwiftCommunity website, one can easily see lots of activity going on.