Here is a list of four fun reasons you should avoid using data types such as Int and String to pass along and process the data in your Swift code. And a list of alternatives to use instead, so you can write much better code with just a few small changes to your current habits.

Note: I’ll troll around a bit because technical articles can be boring.

Note that I use the word Fun in a slightly sarcastic way, as in: “Losing is Fun”.

1. Primitive types aren’t documenting your code

When you see a function definition like this one, do you instantly know what both of the String will actually be?

func getData(for identifier: String) -> String {

Here, String can be anything, both the input String and the output String. If you’re developing the code alone, you will probably remember what is the typical content of those two.

I say probably, because as any developer knows — by Monday you may not remember what the code written on Friday does. It’s something I can promise you. Give this project a few months of a break and it will be easier for you to write the thing from scratch than to try to understand “what the poet had in mind”.

To (try to) ensure the inputs and outputs stay at least a bit clear, you will need to add comments to explain the details of what you expect those Strings to actually contain.

From the above function definition alone we only know we’re looking for some identifier. We may understand from the context of the app what that may be, but what is the result of this function exactly?

Will it give us some kind of person’s name? Or maybe a large chunk of JSON data? Maybe a specific number of animal emojis such as a 🐐 and a 🐠? For no reason. But a String can be all those, so make sure that your code will handle every possible case now. I think you see my point.

In reality, nobody knows what those are until they check the actual code of the function.

We have powerful IDEs (such as Xcode), which provide developers with previews of possible completions. They are useless in this case. Imagine what you would think if you were working on someone else’s code and you stumbled upon the above definition as an Xcode suggestion. My guess is: some rude words will be included in your reaction.

You can’t understand what is happening until you check the code or documentation. And chances are, if you see this kind of String usage, you won’t find any docs for that package or pod or repository. **And also, most docs can’t be trusted because we don’t like to write docs, maintain docs and keep up with the changes in the code. **There is nothing that would force developers to keep the docs and comments in sync.

#swift #swift-programming #programming-languages #ios-app-development #programming

4 Fun Reasons to Avoid Using “Primitive” Swift Types in Your Code
1.05 GEEK