I’m very happy to be on open source movement, and it ‘ll be great to hear about what people have achieved

And @merowing_ also mentioned in Writing Xcode plugin in Swift

Attribution

Writing this was much simpler because I was able to look at other people plugins, mostly those related to console, without them being open sourcing it would be more work to figure this stuff out with hopper.

Open source helps us move forward, learn and share together

The dark side of the Force

Luke: Is the dark side stronger?

Yoda: No, no, no. Quicker, easier, more seductive.

It’s a pain to see plagiarism around

Open source softwares are in fact intellectual properties, and the authors should get acknowledgement for the work that they do.

It’s not fair to take the credit of other’s work and not giving any attribution

By its nature, open source software has a unique relationship with intellectual property rights

One thing that’s not up for debate in most circles is that it’s dishonest and disingenuous to take someone else’s project, modify it slightly, and call it your own.

Further, regardless of whether or not a project crosses that line, it must (by the terms of most open source licenses) acknowledge the original work/author.

And the reaction

It’s always sad to see blatant plagiarism, and I think it really hurts the community more than the author itself. It gives people a good reason to keep the sources private.

Being nice

I often hear people say that

It is easier to find good developer than developer with good attitude

Github also states that

We understand and agree that copying others’ work without permission goes against the spirit of the open source community

Do the right things

Is it MIT ‘s fault? Definitely no

False choice. Giving up freedom does not lead to more security, just less freedom.

Takeaways

• Don’t take things personally
• It’s hard to be perfect, but we can learn to do the right things
• We may do the wrong things, but don’t worry, there ‘ll be help via Issues and Pull Requests

The idea of Signal may originate from Elm Reactivity, and it has now been widely adopted in iOS

Whether it is hot vs cold, Signal vs Signal Producer, Observable vs Enumerable, … it’s good to understand how it gets implemented, so that to have a good sense of how they work

Monad

Basically, Signal and its Result are just monads, which are thing that can be mapped and chained.

Signal makes use of deferred execution callback blocks, and push vs pull is just how the Signal updates its value and the order the callbacks are called

Execution callback block is that we pass a function to another function, and it will get called when appropriated

Sync vs Async

Monad can be in either sync or async mode. Sync is easier to understand, but async is somewhat you’re already familiar and used in practice

Basically,

• Sync: you get the returned value right away via return
• Aync: you get the returned value via callback block

Here is an example of a simple function

Here is an example of Event

Push Signal

Take a look at my Push Signal, called Signal, it is like how Promise A+ Then works

Callbacks

Given a chained signals like this

A -(map)-> B -(flatMap)-> C -(flatMap)-> D -(subscribe)

• The idea is we send event to the source signal, and it propagates events through via callbacks.
• Triggered by sending event to the source signal.
• We must keep A as it keeps the others around
• We subscribe the last D
• We send event to the first A
• A ‘s callback gets called, it it in turn calls callback of B with the result of A ‘s map, then B ‘s callback calls C ‘s callback with the result of B
‘s flatMap, …

Pull Signal

Take a look at my Pull Signal, called Future

Implementation

Here operation is a task, when called and completed, will notify its completion

Callbacks

Given a chained signals like this

A -(map)-> B -(flatMap)-> C -(flatMap)-> D -(subscribe)

• The idea is we subscribe to the final signal D, and it cause the previous signals to action.
• Triggered by subscribing to the final signal.
• We must keep D as it keeps the others around
• We subscribe the last D
• D ‘s operation actions, and it cause C ‘s operation to action, … then A ‘s operation actions. It is in A that the task is performed (like fetching network, retrieving database, file access, heavy computation, …) to get the result, and A ‘s completion gets called. Then A’s completion calls B ‘s completion with the result mapped by B ‘s map, … all the way to the subscriber ‘s completion block

Haskell is notorious for currying, and Swift has currying, too

I love ReactiveCocoa, RxSwift and I always take time to dig into it. The other day, I was practise making Signal based on this talk UIKonf 2015 - Jens Ravens: Functional Reactive Programming without Black Magic

Take a look at my repo Signal

filter

I was making a filter for a Signal. The idea of filter is that we should update signal if the Event is Next with right filtered value

Signal.swift

2 params

But having Event as another monad, I think it should be more encapsulated if that switching logic gets moved into the Event. Here the filter takes 2 params

Event.swift

Signal.swift

Currying

With currying, we can make filter a more abstract function, and defer the decision to pass the callback param. It is a little carried away but I find it helpful this way

Now filter accepts 1 param, and it returns a function that takes callback as its param

Event.swift

Signal.swift

Curry syntax in Swift 2

Swift 2 supports curry syntax function

No more curry syntax in Swift 3

You may want to find out

Reference

NSNotificationCenter is like central hub where notifications are posted and received by any parts of the app

Registering

Registering for notification n times, you get notified n times

debugDescription

As of iOS 9+,

NSNotificationCenter and NSDistributedNotificationCenter will now provide a debug description when printing from the debugger that will list all registered observers including references that have been zeroed out for aiding in debugging notification registrations. This data is only valid per the duration of the breakpoint since the underlying store must account for multithreaded environments. Wildcard registrations for notifications where the name or object that was passed to the addObserver method family was null will be printed in the debug description as *.

Observer

addObserver(_:selector:name:object:)

Adds an entry to the receiver’s dispatch table with an observer, a notification selector and optional criteria: notification name and sender.

• NSNotificationCenter holds weak reference to its observer
• Regular notification centers deliver notifications on the thread in which the notification was posted

addObserverForName(_:object:queue:usingBlock:)

Adds an entry to the receiver’s dispatch table with a notification queue and a block to add to the queue, and optional criteria: notification name and sender.

• The returned of this method is an opaque object to act as the observer, and NSNotificationCenter holds a strong reference to this object
• Avoid strongly capturing objects in the block. See NSNotificationCenter with blocks considered harmful

When to unregister ?

The idea is to unregister as soon as we don’t need to receive notifications. Most of the time, it is our deinit

Before an object that is observing notifications is deallocated, it must tell the notification center to stop sending it notifications. Otherwise, the next notification gets sent to a nonexistent object and the program crashes

iOS 9+

In OS X 10.11 and iOS 9.0 NSNotificationCenter and NSDistributedNotificationCenter will no longer send notifications to registered observers that may be deallocated

This means that observers are not required to un-register in their deallocation method

However,

Block based observers via the -[NSNotificationCenter addObserverForName:object:queue:usingBlock] method still need to be un-registered when no longer in use since the system still holds a strong reference to these observers

So we must call removeObserver on the returned observer object

Synchrony

A notification center delivers notifications to observers synchronously. In other words, when posting a notification, control does not return to the poster until all observers have received and processed the notification

If you have performance problem of posting notifications to large number of observers, consider using

• dispatch_after
• Many NSNotificationCenter
• NSNotificationQueue

NSNotificationQueue

• Enqueuing methods return immediately
• Associated with the run loop modes
• There ‘s defaultQueue for the current thread

Reference

Christmas is when we I have the most special feeling. The cool air, the snow, the reunion, the church bell ringing, …

(From google)

It ‘s beginning to look a lot like Christmas. First with Xcode

Xmas

Xmas is an Xcode plugin that shows Xmas picture along with wishing message whenever a build succeeds

How it works

Swift

• Try to do much of the job in Swift as possible

DVTKit

• Xcode uses DVTBezelAlertPanel to display alert. So we swizzle its initWithIcon:message:parentWindow:duration:
• DVTBezelAlertPanel is from DVTKit. I thought about importing run time header and just extension it. But I find swizzling in Objective C a much more easier solution

NSVisualEffectView

• It seems that NSImage added to the panel ‘s NSVisualEffectView had it template set to YES again, hence causing the image into template color with the panel background color
• This happens in the init method. So we must change template back to NO after init happens

And, Merry Christmas to you and your family

The Marvel world

Ant Man

We know Ant Man is Hank Pym

Everytime HankPym is created, he always uses the Ant Man suit. This time he is so coupled to the role Ant Man

More suits

Well, he does not have to be too dependent on the Ant Man suit. We know Hank Pym is a genius scientist, he has more suits to use. Let’s make it decoupled

Using Dependency Injection

Now Hank Pym can be more flexible on which suit to use.

Dependency Injection

The technique we just saw is called Dependency Injection, in which Hank Pym does not need to create the Suit, it will be provided through constructor or property.

Dependency Inversion Principle

In the first example, Hank Pym is dependent on the concrete implementation of the Suit

In the second example, both Hank Pym and the suits are dependent on the Suit protocol. This way Hank Pym only knows about the Suit protocol, and future suits must be crafted to that it conforms to the Suit protocol

This way the dependency is inverted

High level modules should not depend upon low level modules. Both should depend upon abstractions.

What is the high level policy? It is the abstractions that underlie the application, the
truths that do not vary when the details are changed

Inversion of Control Container

You may ask yourself Why is Inversion of Control named that way?

Framework vs library

People said “the framework calls you but you call the library”

Command line vs GUI

For example, in an old school menu, you might have:

thereby controlling the flow of user interaction.

In a GUI program or some such, instead we say

You how have a brief understanding of how IoC means

IoC container

In the 2nd example of the Suit protocol, you can see how there is a inversion of control. What if there is a container that contains all the Suit conformances?

Let’s use my Resolver

Quite helpful, right? :]

Features

Actually, IoC container helps you more than that.

• Circular Dependency Injection
• Auto Injection
• Object Scope

There are some IoC containers in Swift

Swinject

Swinject requires explicit type declaration. It has SwinjectStoryboard, which helps configuring the dependency for your view controller

Dip

Dip leverages generic and encourage protocols

You ‘ll learn a lot just by reading Dip source code, on how factory and factory type are stored and checked using generic

Build your own simple IoC container

You may have discovered, that the idea of all those framework is to use closure as factory method

All we have to do is to store these factories closure

Take a look at my gist SimpleResolver.swift

Reference

Here are some of my notes when diving into Swift

Default parameter reorder

If a function arguments have default values, you can reorder them at call site.

Note that the first parameter num1 must have external name

Be careful with generic

Here is when I’m trying to do a Resolver

Here I mistakenly use it, because generic can accept any type, even closure

And now factory.dynamicType is of type () -> () -> String, not what I expect () -> String

Short notation works for any static member

We can also .init because the type of the property is already specified

Resolving generic type

Supposed we have contrived method like this, which does not accept any parameter

We can use as to resolve the type, or specify the type

You can learn more when reading Dip

Reference instance method

Supposed we have

We can make a reference to that instance method

We can see that ref is of type Cat -> () -> ()

precondition

Check for a condition, works even in release mode.

strideof

In C, the sizeof operator returns the size of any variable or data type. In Swift, you use the sizeof function to get the size of a given type, or the sizeofValue function to get the size of the type of a given value

Arguments are tuple

• Tuple as Function arguments

• Tuple elements must be the same number, of the same types, and have the same external parameter name as in function

Reference

Swift is open source, here at swift and Swift.org. And for now it uses Apache license

There is a joke on this pull request I think we should use GPL v3 instead, it’s the future of open source.

When developing iOS apps, most of the libraries I use are on MIT licenses, a permissive license, which is good :]

MIT vs GPL vs Apache

These have many things in common

• Commercial Use: This software and derivatives may be used for commercial purposes.
• Distribution: You may distribute this software.
• Modification: This software may be modified.
• Private use: You may use and modify the software without distributing it.
• License and copyright notice: Include a copy of the license and copyright notice with the code.

But

GPL is Disclose Source: copyleft license that requires anyone who distributes your code or a derivative work to make the source available under the same terms.

Apache is Patent Grant and State Changes: Indicate significant changes made to the code

MIT is simple, permissive. You can do anything you like