قالب وردپرس درنا توس
Home / IOS Development / Swift Tips: Refactoring to Associated Values

Swift Tips: Refactoring to Associated Values



We are about to rewrite our Swift Talk backend from Ruby to Swift. Instead of trying to get everything right right away, we usually transfer things by writing Swift code with a very similar structure to the Ruby Code. We make sure everything works as expected, and only then we reflect the code to be more Swift-like.

As an example, we display the user one of four things on the Episode page:

  • "Become a subscriber to download episode videos."
  • "Download episodes do not use any download credits."
  • " You have (creditsLeft) downloaded credits again "
  • " No Download Requirement. You will receive new credits during the next billing period. "

In Ruby the four cases were modeled as an enum and we did the same in Swift: [1

9659008] enum DownloadStatus {
the case notSubscribed
reDownload case
case canDownload
case noCredits
}

To generate the text above, we can write an extension on DownloadStatus :

  extension DownloadStatus {
func text (credits: Int) -> String {
change yourself
// ...
}
}
}

This seems as expected, but after using it for a while, we realized that it exceeded creditsLeft everywhere – from the database to the "controls" layer to the display of this method, be a little annoying. It's also a little annoying to make up a value for the notSubscribed case. In fact, the only place where we need it is in the canDownload case.

To correct these annoyances, we refactored our DownloadStatus enum to include an associated value:

  enum DownloadStatus {
the case notSubscribed
reDownload case
case canDownload (credits: Int)
case noCredits
}

With this in place, we do not need to transfer creditsLeft separately, we can include it directly in the canDownload case. This also makes it possible to write text (creditsLeft :) as a calculated property text :

  was text: String {
change yourself
// ...
}
}

Changing our code to use associated values ​​gives us clearer code, and more importantly, instead of sending two parameters around in multiple places, we enter the other parameter in DownloadStatus enum.

To learn more about enums, take a look at our books: Functional Swift shows how enums can help you write easier code, and Advanced Swift provides a more thorough account of how they work.

You can purchase both books as part of Swift Essentials bundle, with a small discount to say thank you. 🙏


Source link