Unexamined life is not worth living, find the good and evil

Thursday evening and It’s 6 PM, walking down to home after the gym session, and I see a call from my younger sister where she talked about people, she said why it’s so hard to examine someone in life. (Inspect someone thoroughly to determine their words and mindset is the same).

I tried to give her a nice example which I learned from Socrates who was a great greek philosopher from Athens. Socrates is credited as a founder of Western philosophy and the first moral philosopher of the Western ethical tradition of thought.

In one of his books, he talks about the Dialectic method, (Disclosure Between two or more people holding a different point of view about the subject but wishing to establish the truth through reason argumentation). Same way in life the subject is not important, it’s always good to take a standpoint of someone who knows nothing 🤷🏻‍♂️ yeah nothing. And asking questions exposes the contradiction in the argument and the gap in the statement.

By doing we can find the good and the evils. The good who is truthful and has a clear understanding about the statement(s) they are making and the evils the one who make the false commitments (or I would say Propaganda).

I know you may be aware of it, but it’s important to take a pause and give a thought about it.

The same principle we can relate to life. The only life worth living is good. I can only live a good life if I know what Good and Evil are. As we discussed before. Good and evil or not related they are absolute that can only be found by the process of questioning and reasoning. In this way, morality and knowledge are bound together. An unquestioning life is one of ignorance without morality.

In the end, I would say a good life is Achieving peace of mind as a result of doing the right thing, rather than living according to the moral codes of society. and the right thing can only be determined through rigorous examination.

Thanks for reading.

The High 5 habit book summary

This book helps you to understand that

  • why changing your mindset is like doing the laundry work.
  • how the high fives can change the structure of your brain.

How do you feel what you wake up? most of us feels like crawl back beneath the covers for a few more hours of rest.

What if there is a way to change that? let’s learn how to harness the power of the High 5 Habit.

Do you have those morning minutes when you criticise yourself and find fault with you body? If yes let’s start the day by High-fiving your reflection, when you look into the mirror tomorrow morning, you will face a choice. Either spend time mulling over your failing or take a minute to congratulate yourself.

Some scientific reasons; when you high-five yourself in the mirror, your brain understands that something exciting is there and it starts paying the attention.

Another point to highlight, brain also has a filter – Reticular Activating System (RAS) which filters the information the brain processes, to make sure only relevant data reaches the level of conscious thought.

So what is the lint that’s blocking your RAS? it’s the self-limiting thoughts.
Rejection, setback or some insult – all can get trapped here which leads mind to focus on negative information while disregarding the positive. High 5 technique we can use to make the RAS work in our favour.

Key message: Interrupt your thoughts, use a mantra and act like the person you want to become.

There are three key steps in training your RAS to see the world differently

  • Interrupt your old thinking process; take a pause and ask yourself; “wait, I am not thinking about it”
  • Mantra; Choose something that you think is both encouraging and accurate, like “”

    “A mantra is not something that you utter. It is something that you strive to become because unless you become the key, existence will not open up for you. Becoming the mantra means you are becoming the key.” – Sadhguru

    Benefits of Chanting Mantras and the Science Behind It
  • Finally act like a person you want to become;

Thanks for reading!

Power of Switch case statements in Swift, Interval matching, type checking, value binding, where clause, tuple, if case let and the pattern matching

In this post we will go through some amazing and useful tips that we can do with the Switch control flow statement.

Some benefits with using Switch statements rather than if

  1. Switch statements are exhaustive, which means you must have to add a case for every possible value to check or you must have a defaultcase.
  2. Switch read the value once and compare with all case, which help to improve the performance.
  3. Switch cases allows the advanced pattern matching which will we see later in this post.

To match a value against a number of cases

switch statusCode {
	case 200:
	// 200 code here
	case 404:
	// 500 code here
	case 500, 501:
	// 500 or 501 code here
	default:
	// default handling code
}

Extending the functionality

extension Int {
	static let resourseNotFound = 404
	static let serverError = 500
	static let ok = 200
}

switch statusCode {
	case .resourseNotFound:
	// 404 code here
	case serverError:
	// 500 code here
	default:
	// default handling code
}

Interval matching

switch statusCode {
	case 200...201:
	// code here to handle 200, 201
	case 400..499:
	// code here to handle 400 to 499
	case 500..<599:
	// code here to handle 400 to 499
	default:
	// default handling code
}

Type checking

switch discount {
	case is Int:
	// discount is int type
	case let discount as String:
	// discount is String type
	default:
	// default handling code
}

Value Bindings ( name the value(s) matches to the temporary constant(s) )

let point = (x: 10, y:50)

switch frame {
	case (_, let y):
	// somewher on x where the y value is `y`
	case let (x, y)
	// somewhere at `x` and `y`
}

Implement with enum

enum {
	case success
	case error(code: Int)
}

switch error {
	case .success:
	// success here
	case .error(let code):
	// error with status code here
}

Chip in the where clause

enum {
	case success
	case error(code: Int)
}

switch error {
	case .success:
	// success here
	case .error(let code) where code == 404:
	// error with status code 404 here
	case .error(let code) where code == 400:
	// error with status code 400 here
}

with tuple

let frame = (x: 10, y:50, width:100, height: 100)

switch frame {
	case (_, _, let width, _) where width == 100:
	// width is 100 here
	case (_, _, let width, height) where width == height:
	// where height is equal to width
	case .error(let x, let y, let width, let height)
	// any case here
}

If case let

if case let .error(code) = response { }

// alternate form 
if case .error(let code) = response { }

// with extra condition check
if case let .error(code) = response, code == 500 { }

// with guard statement
guard case let .error(code) = response {
	return
}

// with for-in loop
for case let code in response {}

// with for-in loop + where clause
for case let code in response where code == 500 {}

Fallthrough

switch error {
	case .success:
	// success here
	fallthrough

	case .error(let _):
	// failure
	fallthrough

	case default:
	// request finished.
}

How to write the Unit Test for static functions?

Recently I came across a requirement where we need to integrate App Tracking Transparency (ATT for short) which is a new feature of iOS, iPadOS and for the tvOS 14.5 that requires applications to ask for permission if they track user activity across other companies apps (where they access the unique adverting identifiers).

So we did it but since we love TDD and we try to make sure whatever new feature/changes we are doing should have unit test.

If you see the Apple documentation here it says requestTrackingAuthorization(completionHandler:) is the function to request for user authorisation to access app-related data.

class func requestTrackingAuthorization(completionHandler completion: @escaping (ATTrackingManager.AuthorizationStatus) -> Void)

Which is a class function with the completion handler, So how will you test it?

Give a pause and think if you have an answer for it already ( Previously I used to integrate some 3rd party library to mock the static func).

OK let’s see the trick.

  1. Create a protocol with the same signature of the static func we want to test.
protocol PrivacyManagerBridge {
    static func requestLocation(completionHandler completion: @escaping (Bool) -> Void)
}

2. Let the ATTrackingManager to conform the protocol

extension ATTrackingManager: PrivacyManagerBridge {}

3. Create a new protocol with the same signature but it’s a instance func, create a class which conform the protocol ( let’s say the class responsibility is to handle the privacy with in the app) so I gave the name AppPrivacyManager

protocol AppPrivacyManagerContract {
    func requestTrackingAuthorization(completionHandler completion: @escaping (ATTrackingManager.AuthorizationStatus) -> Void)
}

class AppPrivacyManager: AppPrivacyManagerContract {
    private var trackable: PrivacyManagerBridge.Type!

    init(trackable: PrivacyManagerBridge.Type = ATTrackingManager.self) {
        self.trackable = trackable
    }

    func requestTrackingAuthorization(completionHandler completion: @escaping (ATTrackingManager.AuthorizationStatus) -> Void) {
        self.trackable.requestTrackingAuthorization(completionHandler: completion)
    }
}

If you see when we initialise this class, it takes a parameter which is PrivacyManagerBridge.Type and that’s the trick and now when it comes to test this piece of code we can create a mock by conforming the PrivacyManagerBridge

class ATTrackingManagerMock: PrivacyManagerBridge {
    static func requestTrackingAuthorization(completionHandler completion: @escaping (ATTrackingManager.AuthorizationStatus) -> Void) {
        // Return whichever flow you want to test.
        completion(.denied)
    }
}

Let’s write the test.

let privacyManager = AppPrivacyManager(trackable: ATTrackingManagerMock.self)
privacyManager.requestTrackingAuthorization { result in
    // result here
}

That’s it, Thanks for reading.


Here is the Github Gist.
https://gist.github.com/buntylm/9d878d0219dd307667f51bbb71158576

FAQ: How to combine two dictionaries in Swift?

func merging<S>(_ other: S, uniquingKeysWith combine: (Value, Value) throws -> Value) rethrows -> [Key : Value] where S : Sequence, S.Element == (Key, Value)

Creates a new dictionary instance by merging key-value pairs in a sequence. Pass a sequence of key-value pairs and a closure that takes the current and new value for duplicates keys, if no duplicates it should not be triggered.

let a = ["1": "2", "2": "4"]
let b = ["2": "1", "3": "5"]

let combine = a.merging(b, uniquingKeysWith: +)
// Output: ["2": "41", "1": "2", "3": "5"]


let takeNew = a.merging(b, uniquingKeysWith: { _, new in
    new
})
// Output: ["2": "1", "1": "2", "3": "5"]


let keepCurrent = a.merging(b, uniquingKeysWith: { current, _ in
    current
})
// Output: ["2": "4", "1": "2", "3": "5"]

Thanks for reading.

Lessons that I learned from good programmers around me.

If you new here, I’m @Buntylm, Singapore-based programmer 👨🏻‍💻. Currently working on Swift developing apps for iOS devices and Web APIs using Java and Golang.

👨‍💻 Below are the lessons that I learnt from good programmer around me.

  • Importance of software design patterns.
    • Inspiration
      • Design patterns don’t provide solutions, they inspire solutions.
      • Patterns explicitly capture expert knowledge and design trade-offs and make this expertise widely available.
    • Improve developer communication, easy to describe a very specific structure of code
    • Help document the architecture of a system.
  • Essentially code that is considered good.
    • Does what it should.
    • Follow a consistent style
    • Easy to understand and test.
  • Code quality measurement
    • Reliability, system will run without failure over a specific period of operation.
    • Testability, relies on how well you can control, observe, isolate, and automate testing
    • Reusability, measures whether existing assets, piece of code can be used again.
  • Programming languages – don’t be language specific. Always learn new language since the technology is changing drastically.
  • Basic of data structure and algorithms is necessary.
  • Become an expert at debugging. Don’t use a debugger when it comes to finding a bug; make use of your mental model and take help from the system logs.
  • Speak up ask questions
  • No – say goodbye to being a people pleaser and learn how to confidently say no to someone without feeling bad about it.
  • Expertise in Git (provides cheap local branching, convenient staging areas, and multiple workflows). Always use source control.
  • Make a working release/build in one step.
  • See things around you, work that you are doing on daily basis and ask you, can I automate it ? Pick the right tool. It can save you a lot of time in the long run.
  • Always maintain a bug database.
  • Learn and try new things. 
    “The day you stop learning is the day you begin decaying.”
  • Minimise your distraction when you are at your desk, try out some tools like Be Focused, make use of some app/website blocker if you cannot control, and turn-off the notifications. Read some interesting books like this Getting Things Done.
  • Process
    • Agile (approach discovering requirements and developing solutions through the collaborative effort of self organising and cross functional teams and their customers. wiki
      Simple definition to describe Agile: A time boxed, iterative approach to software delivery that builds software incrementally from the start of the project, instead of trying to deliver it all at once near the end (every sprint you will some working software/product).
  • xDD which TDD/BDD. Always write test-cases. Think, solve the problem, write test-cases and write code. Later refactor to improve it further.
    • Write a failing test.
    • Make it pass.
    • Refactor to improve your code.
    • Repeat.
    • Techniques
  • Feynman Learning Technique:
    • Choose a concept you want to learn about.
    • Pretend you are teaching it to a student in grade 6.
    • Identify gaps in your explanation, and go back to the source material to better understand it.
    • Review and simplify.

Thanks for reading it.
Do share if you like it, let me know if you have any comments. :✌️

Don’t be foolish | Mind Manipulation

Manipulating others is a best way to get what you want from others, but do you know people around you tricking some techniques to make you fool, and getting what they want from you.

First let’s talk about what is the mind manipulation, when it comes to decision making we have 2 systems in our brain. System 1 operates automatically and quickly, with little or no effort. System 2 allocates attention to the effortful mental model. People are using few hacks to not to allow us to use System 2 where we don’t think much and do what they want us to do.

The Halo Effect, A type of cognitive bias in which our overall impression of a person influences how we feel about their character. It’s also called “physical attractiveness stereotype” or “what is beautiful is also the best” principle. 

When we like someone we just ignore their bad quality and always appreciate them. If they make some mistake we always say, ah that fine, we all are human we make mistakes. we always follow their advice, without giving a single thought. At the workplace, bosses may rate the employees on the perception of a single characteristic rather than the whole of their performance and contribution.

You will notice this trick is used by politicians, celebrities where they have huge PR team to refine their image, so that you will feel attraction towards them.

Priming, Let’s start with an example first, If i expose a word to you “YELLOW” it will evoke a faster response to the word “BANANA” if you like fruits or “SCOOT” if you air travel a lot. If I write APPLE and ask you to fill in the gap GR_ _ _. most of the us will say GRAPE.

Picture Credit : Google.com

This is the technique used for marketing to sell the product. You can hit Google and see there are thousands of studies on Priming, one of them which i like a lot is Music and Wine testing (Significant associations between the musical stimulus genre and participant change in wine selection).

The Hindsight Bias, Focus on the cartoon for 10 seconds and see you do you think about it.

Picture Credit : Google.com

Tendency to look back at an unpredictable event and think it was easily predictable, I knew it is going to happen, i knew Trump is going to win the US elections. Nope you knows nothing, we all have people around us like this. You are trying to be an expert of something that has happened already, it can case distortions of our memories of what we knew or believed before an event occurred, also don’t trust people like this.

Thanks for reading it.

The Social Dilemma (2020) on Netflix.

The Social Dilemma, one of the most splendid documentary I have seen in a while, shows the rise of social media and the damage it has caused to society.

Reasons why you should watch this documentary to understand.

  • If the you are not paying for the product, then you are the product.
Picture credit: Google

The Goal is to increase the user’s screen time, each of your activity online is being tracked, every like you hit, every comment you post, every video you watched, how long you watched, what leads you to this action, each and every small action you took consciously or unconsciously. Once companies have this information then artificial intelligence comes into the picture.

Artificial intelligence (AI) refers to the simulation of human intelligence in machines that are programmed to think like humans and mimic their actions.

Since companies have all the information on how you behave, what actions you take on certain conditions, they have built AI for each and everyone which gives the content feed what as a user you will like, creates a personalised experience for everyone. Now the even more dangerous thing comes in the picture called Machine learning (that provides systems the ability to automatically learn and improve from the experience without being explicit programmed) which learn from action and improves the judgement accordingly to increase the accuracy.

Picture credit: Google
  • There are only two industries that call their customers ‘users’, illegal drugs and software.
    • Engagement: This is the important aspect, to keep user more engaged by sending them the notification, showing the information that user want to see. The time you spent on one video is also tracked to analyze your interest on the feed.
    • Growth: Friends suggestion, allowing friends to tag in, one more the very common way “Say Hi” to your friend who recently joined messenger.
    • Revenue: Ok, Just login to gmail and go to Google search, search a product and you will see the same product ads will start appearing everywhere for you, if you don’t take action later you will see the same product with some discount.
  • Age of disinformation/false news can lead us to the civil war.
Picture credit: Google

Due to large number of user no application can distinguish between the truth and the fake news. [Study: On Twitter, false news travels faster than true stories] MIT study found that falsehood diffuses significantly farther, faster, deeper, and more broadly than the truth, in all categories of information, and in many cases by an order of magnitude.

Thanks for reading it.

How to perform throttling in Swift, Debounce.

What is Throttling all about, it’s a process responsible for regulating the rate at which application processing is conducted (doesn’t matter statically or dynamically). Wikipedia

A very common use in iOS, when you have a search bar which takes input from user and sends off a request for search results every time. For a long query it may cause lot of requests to be sent on server to process (performance will be different for slow vs fast typing user & also depends on internet connection).

Another use case that I faced today is to log an impression when user sees the TableViewCell. I found and interesting example on Github. I created an extension for this to make use of it everywhere.

Create a protocol.

protocol Throttable {
    func perform(with delay: TimeInterval,
                 in queue: DispatchQueue,
                 block completion: @escaping () -> Void) -> () -> Void
}

Provide the default implementation using the extension.

extension Throttable {
    func perform(with delay: TimeInterval,
                 in queue: DispatchQueue = DispatchQueue.main,
                 block completion: @escaping () -> Void) -> () -> Void {
        
        var workItem: DispatchWorkItem?
        
        return {
            workItem?.cancel()
            workItem = DispatchWorkItem(block: completion)
            queue.asyncAfter(deadline: .now() + delay, execute: workItem!)
        }
    }
}

Responsibility of this function is just to return a function, when you call the returned function.

  • It cancels the exiting workItem if exists (magical Optional).
  • Creates a new DispatchWorkItem with the completion block.
  • And the queue calls the workItem with given delay.

And that’s how it works, Just conforms the Throttable protocol wherever you want.

class UserInputHandler: Throttable {
    let triggerAPI = perform(with: 1.0) {
        print("Fetch Search Result")
    }
    
    func didReceiveInput() {
        triggerAPI()
    }
}

Here is an easy example to integration it with UIViewController

class SearchViewController: UIViewController, Throttable {
    @IBOutlet weak var searchTextField: UITextField!
    
    lazy var triggerAPI = perform(with: 1.0) { [weak self] in
        
        guard let searchText = self?.searchTextField.text, !searchText.isEmpty else {
            return
        }
        
        print("API Request to fetch result for \(searchText)")
    }
}

extension SearchViewController: UITextFieldDelegate {
    func textField(_ textField: UITextField, shouldChangeCharactersIn range: NSRange, replacementString string: String) -> Bool {
        triggerAPI()
        return true
    }
}

Thanks for reading
Find more Swift Tips and Tricks on Github.

How to check API availability in Swift, iOS / macOS / watchOS / tvOS SDK

What is Availability checking?

Today Apple leads the world of innovation with iOS, MacOS, watchOS and tvOS, and every year we see new operating system release with more enhances, and new technologies.

So all the features Apple releases is coupled with the OS releases (for example Sign-in with Apple is available on iOS 13 and above only). As a developer is highly recommend for us to delivery one binary which support latest as well as old operating system.

So this availability check is Swift gives us the power to check weather the user running a specific version or not.

Swift API to check the OS version?

class LoginViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        initLoginView()
    }

    private func initLoginView() {
        //initialise login view
        
        guard #available(iOS 13.0, *) else {
            return
        }
        
        let authButton = ASAuthorizationAppleIDButton()
        // integrate Sign in with Apple
    }
}

Code snippet shows that we are initializing a LoginView for user to login, and making use of #available API call to check the version, if it’s iOS 13.0 and above we do add “Sign in with Apple” which is only available in iOS 13.0 and above.

Swift also provides us an declaration attribute (there are two kind of attributes in Swift, one that apply to declarations and another to types) to declare that this call or function is available on which iOS version.

@available(iOS 13, *)
func initSignInWithApple() {
// use AuthorizationService framework to integrate Sign in with Apple.
}

These are the arguments we can make use in @available attribute.

  • iOS 
  • iOSApplicationExtension
  • macOS
  • macOSApplicationExtension
  • watchOS
  • watchOSExtension
  • tvOS
  • tvOSApplicationExtension
  • swift

An asterisk (*) to indicate all platforms.

Few interesting use that we can make use.

@available(*, unavailable) – Indicates that the declaration is not available on given platform.

@available(*, introduced) – Indicates the first version when the declaration was introduced.

@available(*, obsoleted) – Indicates the first version platform/language in which the declaration was obsoleted.  

@available(*, message) – A message that the complier displays during the warning or error.

@available(*, renamed) – A message that the complier displays during the warning or error about the renaming.

Interesting example that I really like from Swift documentation.

// A protocol defined in first release.
protocol ConfigProtocol {

}

Would like to change the name in next release?

// change the name.
protocol AppConfigProtocol {

}

@available(*, unavailable, renamed: "AppConfigProtocol") 
typealias ConfigProtocol = AppConfigProtocol 

In this case, complier will start giving you a error, also a fix for you.

‘ConfigProtocol’ has been renamed to ‘AppConfigProtocol’

Replace ‘ConfigProtocol’ with ‘AppConfigProtocol’

Thanks for reading.