Home Articles

Swift Tips

Unlock the Power of Swift Programming with Expert Strategies and Techniques.

1: Unwrapping swift optionals with map/flatmap

The usual way of unwrapping optionals is using if let or guard statement

Unwrapping Optional Binding

Same unwrapping functionality can be achieved through higher order functions map/flatmap

Unwrapping Higher Order Functions

2: When swift compiler doesn’t create default initializer?

Swift Compiler Header Image

Swift compiler doesn’t create default initialiser if one of the property in struct is declared private

Private Default Initializer

Default initialiser is also not created when any custom initializer is defined by us

Custom Default Initializer

3: Codable property mapping to keys of API response with different name

Sometimes we want to use different property names in front end than one defined in API response. We could easily achieve it without writing custom decoder or encoder by just specifying CodingKeys

CodingKeys

id from json easily got converted to identifier by just mentioning CodingKeys

4: Write Self-Documentary code using unit tests

Often people write comments in code which they think is self-explanatory for anyone reading code. You can abuse comments if in future you modify code and forget to update comments.

Documentary Unit Tests

On modifying code, tests would break. Message in the test clearly demonstrates that the expected path is...

There are fewer chances that you will forget to modify message if the expectation is changed now.

5: Prefer Enum over Optional && Bool combinations

Optionals only represent two possible states i.e. true or false, enums are able to specify and combine multiple stateful properties into a single state representation.

Prefer Enum over Optional && Bool

In above screenshot, we need to take care of sending successValue explicitly nil when success is false, setting wrong value can lead controller in a wrong state.

Prefer Enum over Optional && Bool

6: Handle Response using Result Type

Usual Approach

Apart from network request, it can be used at several places where you have to return both success or failure or only success value denoting this function returns only success.

Usual Approach

Result type also provides several functions like

  1. map and flatMap to transform success
  2. mapError and flatMapError to transform error.
  3. It also provides get() which returns success value when there is success and throws error when there is failure.

NOTE

To represent operations that, when they succeed, don’t produce any meaningful result: Result<Void, Error> can be used. Success would be indicated by the following code: .success(()). Failure in same way: .failure(error)

For a function always returns success, you can use Result type with error as Never Result<String, Never>. With this you don’t need to implement failure case in switch case


References

  1. SE-0235 Proposal
  2. Result Type Implementation by Apple
  3. To know more on Never

7: Transforming ResultType into another ResultType

Using map and flatmap to get functional programming style

Usual Approach ResultType

Result type provides map function to transform success value and mapError to transform failure value

Usual Approach ResultType

Elegantly transformed Result type values

Transforming Result Type Success into another type using function.

FlatMap transform only success type so failure type of both functions should match

Usual Approach ResultType

8: XCTest useful utilities

XCTUnwrap, XCTSkipIf and XCTSkipUnless

XCTUnwrap

This function asserts that an expression is not nil, and returns the unwrapped value. This function throws error when expression is nil.

XCTUnwrap

Methods for Skipping Tests

XCTSkip

You can use Boolean condition to evaluate when to skip tests

XCTSkipIf

XCTSkipUnless

Bonus Tip: Now you can throw errors from setUpWithError and tearDownWithError function by mentioning throws keyword

9: Leverage of Compiler Diagnostic Directives

While writing new code also sometimes we need to write //TODO or //FIXME. Issue with them is although they are available in Show document items but we need to check it, doesn’t highlight automatically.

warning and error comes handy here

warning

It can be used to manually trigger a warning on the given line. It’s useful during development to get/give feedback about the current state of your code.

Could be use for:

  1. localization
  2. analytics events
  3. logic clarification

error

It can be used to trigger compile timer error

Most useful when you are handling over work to someone else or while shipping library

Links to check out

  1. Proposal 0196
  2. swift unboxed Swift Diagnostics: #warning and #error

10: Using closures for UIControl Actions

From iOS 14 UIControl action can be specify in closure instead of addTarget

UIControl Actions

Only caveat with closure is memory leak. For large functionality still addTarget is preferred or call function inside addAction closure.

Reference

https://developer.apple.com/documentation/uikit/uicontrol/3600490-addaction

This is a free third party commenting service we are using for you, which needs you to sign in to post a comment, but the good bit is you can stay anonymous while commenting.