Category Archives: Uncategorized

passing closures into functions as completion handlers

http://artsy.github.io/blog/2016/06/24/typealias-for-great-good/

Type aliases allow developers to define synonyms for pre-existing types.
You can use typealias for most any type: classes, enums, structs, tuples, closures, etc.

Here are a few examples:

Defining the handler type

Basically, we want to declare a completion handler that takes in bool as parameter, returns void

Defining the function, and its interface

Declare the function definition. It takes two parameters, url and a handler type, which we declared.

The closure type we declared is CompletionHandler. So we say, the completionHandler takes in closure type called CompletionHandler. It takes in one parameter of bool type, and returns void.

As you can see, we call this closure within the code of our function.

Using the function, defining the closure

Now we use and call the function. At the same time, we define the closure, and pass it in.

Ex – adding two strings together, returning result

typealias in swift 3, closures

http://stackoverflow.com/questions/40183806/defining-typealias-in-swift-3-for-closures

You can’t specify parameter names in closure typealias. So instead of:

You should use:

Downcast upcast using as! as?

demo

http://stackoverflow.com/questions/29637974/whats-the-difference-between-as-as-and-as
http://stackoverflow.com/questions/27570957/swift-difference-as-string-vs-as-string

Setup

Animal

MeatEater

VeggieEater

Upcast

upcast

The upcast, going from a derived class to a base class, can be checked at compile time and will never fail.

Upcast Example

Downcast

A constant or variable of a certain class type may actually refer to an instance of a subclass behind the scenes. Where you believe this is the case, you can try to downcast to the subclass type with a type cast operator (as? or as!).

Because downcasting can fail, the type cast operator comes in two different forms. The conditional form, as?, returns an optional value of the type you are trying to downcast to. The forced form, as!, attempts the downcast and force-unwraps the result as a single compound action.

Use the conditional form of the type cast operator (as?) when you are not sure if the downcast will succeed. This form of the operator will always return an optional value, and the value will be nil if the downcast was not possible. This enables you to check for a successful downcast.

Downcast example

1) To start off, we have a bunch of MeatEaters and VeggieEaters lying around in the heap.

2) We then have an array of Animal reference (base class) pointing to subclasses VeggieEater or MeatEater. We can do this because both VeggieEater and MeatEater are child class of Animal.

3) When we loop through this array of Animals, we need to know whether this Animal reference is a VeggieEater or MeatEater. Essentially, we need to know whether that animal is a meat or veggie eater. In order to do this, we downcast it to MeatEater and VeggieEater.

downcast

as? Type means: cast to this type, if possible, otherwise evaluate to nil
as! Type means: cast to an optional Type, because I know it’s an optional Type. I understand that if it’s not that, a runtime exception is generated

swift delegation

http://stackoverflow.com/questions/40501780/examples-of-delegates-in-swift-3

So why should I use delegation instead of those options?

I will try to make it simple; You should use delegation when you have one to one relationship between two objects.

Just to make it clearer, the goal of talking a little bit about the NotificationCenter is to trying to make sense when to use delegations:

NotificationCenter represents one to many relationship. Simply, It works like: posting a notification on a specific event and any object can observe this notification; Logically speaking, that’s what one to many relationship means.

Imagine that you are building an application that related to playing audios, some of viewControllers should have a view of an audio player, in the simplest case, we assume that it should has a play/pause button and let’s say a button for showing a playlist.

In order for the viewController to control all the different audio players, the viewController must have a delegate. That is, it delegates tasks to that “Audio Player”. We create the protocol like so:

This means that whatever the implementation of the Audio Player is, whether its a mp3 player, or a cloud music cast, or square, or circle, blue, or red, it doesn’t matter. As long as the player conform do this protocol, it can receive control messages from the ViewController. Thus, say we create an audio player called MacAmp, it would be like this:

When we would have the delegate property in the View, so that it can control our MacAmp audio player. Notice:

Using the delegate in Views to control other audio players (such as MacAmp, that conforms to AudioPlayerDelegate)

In AudioPlayerView’s implementation file’s viewDidLoad or init method, you’d connect AudioPlayerView’s.

AudioPlayerView.m

then you use it like so elsewhere in AudioPlayerView.m:

So far so good, the audio player view has its separated UIView class and .xib file, in the wanted viewController you loaded it and added as a subview

But now, how could you add functionality to the both buttons? you might think of: “Simply, I will add an IBAction in the view class and that’s it”, well at the first look, it might sounds ok, but after thinking about it, you will recognize that it is a bad idea if you are trying to handle the event of tapping the button at the controller layer level, in other words, what if each viewController should does a different event for -for example- playlist button? let’s do delegation:

‘weak’ may only be applied to class and class-bound protocol types

https://stackoverflow.com/questions/38841127/why-can-the-keyword-weak-only-be-applied-to-class-and-class-bound-protocol-typ

weak is a qualifier for reference types (as opposed to value types, such as structs and built-in value types).

Reference types let you have multiple references to the same object. The object gets deallocated when the last strong reference stops referencing it (weak references do not count).

Value types, on the other hand, are assigned by copy. Reference counting does not apply, so weak modifier does not make sense with them.

However! One common reason for this error is that you have declared you own protocol, but forgot to inherit from NSObjectProtocol:

The code above will give you the error if you forget to inherit from NSObjectProtocol.

Mutating, value type, and reference type

http://stackoverflow.com/questions/38422781/mutating-keyword-for-function-not-needed

When To Use Mutating Functions in Swift Structs

Modifying Value Types from Within Instance Methods

Structures and enumerations are value types. When assigning a variable onto a value type, Value types are copied. Thus, after the assignment, the two variables have their own value type object. By default, the properties of a value type cannot be modified from within its instance methods. (http://chineseruleof8.com/code/index.php/2017/02/04/value-types-vs-reference-types/)

However, in a value type, if you need to modify the properties of your structure or enumeration within a particular method, you can opt in to mutating behavior for that method. The method can then mutate (that is, change) its properties from within the method, and any changes that it makes are written back to the original structure when the method ends. The method can also assign a completely new instance to its implicit self property, and this new instance will replace the existing one when the method ends.

You can opt in to this behavior by placing the mutating keyword before the func keyword for that method …

Hence, we need to include the keyword mutating to allow a member (e.g. a function†) of a value type to mutate its members (e.g. the member properties of a struct).

Mutating a member of a value type instance means mutating the value type instance itself (self). The address will change.

So the situation of the code is that object Person “ricky” is allocated on the heap. Then the reference is passed into an object of type Bill. Inside the init for the object Bill, it instantiate a new Person object, and copies the data of the “ricky” Person. Thus, this ensures that our Bill object has its own Person object, initiated with data from “ricky” Person object. Thus, when changes in Bill object, it won’t touch the outside “ricky” Person object.

Whereas mutating a member of a reference type instance will not mean the reference of the reference type instance (which is considered self) is mutated. The address stays same.

Hence, since a class is a reference type in Swift, we need not include the mutating keyword in any of the instance methods of your Zombie class, even if they mutate the instance members or the class. If we were to speak of mutating the actual class instance fredTheZombie, we would refer to mutating its actual reference (e.g. to point at another Zombie instance).

[†]: As another example, we may use e.g. mutating getters (get); in which case we need to mark this explicitly as these are nonmutating by default. Setters (set), on the other hand, are mutating by default, and hence need no mutating keyword even if they mutate members of a value type.

Not good. Not readable

Let’s use mutating keyword – Much Better!

lazy loading in swift

ref – http://mikebuss.com/2014/06/22/lazy-initialization-swift/

‘in’ keyword for Swift

http://stackoverflow.com/questions/30379108/swift-in-keyword-in-a-on-a-function

In a named function, we declare the parameters and return type in the func declaration line.

In an anonymous function, there is no func declaration line – it’s anonymous! So we do it with an in line at the start of the body instead.

(That is the full form of an anonymous function. But then Swift has a series of rules allowing the return type, the parameter types, and even the parameter names and the whole in line to be omitted under certain circumstances.)

Closures (escaping and non escaping) in swift

https://swiftunboxed.com/lang/closures-escaping-noescape-swift3/

Closures

Closures in Swift are similar to that of self-contained functions organized as blocks and called anywhere like C and Objective C languages.
In Swift, functions are named closures.

Constants and variable references defined inside the functions are captured and stored in closures. Functions are considered as special cases of closures.

Closures are defined like so:

In the below case it is:

output:
Welcome to Swift Closures

The following closure accepts two parameters and returns a Bool value −

if function expressions are declared and used like so:

then closure expressions are used like this:

Function usage

Thus, functions and closures are first-class objects in Swift: you can store them, pass them as arguments to functions, and treat them as you would any other value or object. Passing in closures as completion handlers is a common pattern in many APIs we all know and love.

When you pass a closure into a function in Swift 3, there’s a new wrinkle: the compiler assumes closure parameters are non-escaping by default. What does this mean? What’s the difference between an escaping and a non-escaping closure?

Non-Escaping Closures

The lifecycle of a non-escaping closure is simple:

  • 1.Pass a closure into a function
  • 2a. The function runs the closure (or not)
  • 2b. The function returns
  • 3. When the function returns, the passed-in closure goes out of scope, thus has not escaped the function. Nothing else can reference it

closure-noescape

Notice the closure has not escaped the body of the function. When the function ends, the passed-in closure goes out of scope and there were no additional references made to the closure.

If you remember your memory management, you might say the retains and releases are balanced; the closure object’s retain count after the function returns is the same as it was before the function was called.

Escaping Closures

Inside the function, you can still run the closure (or not); the extra bit is the closure is stored some place that will outlive the function. There are several ways to have a closure escape its containing function:

  • Asynchronous execution: If you execute the closure asynchronously on a dispatch queue, the queue will hold onto the closure for you. You have no idea when the closure will be executed and there’s no guarantee it will complete before the function returns.
  • Storage: Storing the closure to a global variable, property, or any other bit of storage that lives on past the function call means the closure has also escaped.

closure-escape

References
A first class object is an entity that can be dynamically created, destroyed, passed to a function, returned as a value, and have all the rights as other variables in the programming language have. Depending on the language, this can imply: being expressible as an anonymous literal value.

When you call someMethod with the closure, note that someProperty is a property on ClassB. What happened to the requirement about always using self in closures? That requirement only applies to escaping closures and since non-escaping is the new default, you’ll have no problems running this code in Swift 3.

The closure is still capturing self but since the closure won’t live past calling someMethod, the compiler knows there’s no retain cycle risk: there’s no chance that closure parameter will make it out.

On the other hand, what if the method declaration looked like this:

Now it’s a different story. Who knows what the method will do with the closure: store it, queue it somewhere? When you call this method and provide a closure that references a property, you must explicitly write self inside the closure body to remind yourself about the capture.

Capturing as weak

Retain cycles, weak, unowned in Swift

Note that closure parameters are non-escaping by default. However, closures still strong outside properties. Hence, you’ll need to do a weak self:

The Least You Need to Know, and other examples

https://stackoverflow.com/questions/39433221/why-do-closures-require-an-explicit-self-when-theyre-all-non-escaping-by-defa

In Swift 3, closure parameters are non-escaping by default; you can use the new @escaping attribute if this isn’t what you want. Non-escaping closures passed in as arguments are guaranteed to not stick around once the function returns.

in Swift 3, only closure function arguments are non-escaping by default (as per SE-0103). For example:

As closure in the above example is non-escaping, it is prohibited from being stored or captured, thus limiting its lifetime to the lifetime of the function foo(_:).
This therefore means that any closure parameters it captures are guaranteed to not remain captured after the function exits – meaning that you don’t need to worry about problems that can occur with capturing, such as retain cycles.

However, a closure stored property (such as bar in the above example) is by definition escaping (it would be nonsensical to mark it with @noescape) as its lifetime not limited to a given function. It (and therefore all its captured variables) will remain in memory as long as the given instance remains in memory. This can therefore easily lead to problems such as retain cycles, which is why you need to use an explicit self in order to make the capturing semantics explicit.

Let’s say we have this code:

In this example code, it will create a retain cycle upon viewDidLoad() being called, as someClosure strongly captures self, and self strongly references someClosure, as it’s a stored property.

Retain cycles, weak, unowned in Swift

ref – http://www.thomashanning.com/retain-cycles-weak-unowned-swift/

  • By default, each reference, that points to an instance of a class, is a so-called strong reference.
  • As long as there is at least one strong reference pointing to an instance, this instance will not be deallocated.
  • When there’s no strong reference pointing to that instance left, the instance will be deallocated

output:
init
deinit
Program ended with exit code: 0

retain-cycle-image-1

testClass has a strong reference to an instance of TestClass. Hence TestClass instance is +1.

If we now set this reference to nil, the reference pointer will away from the TestClass object, and point to nil. TestClass instance is now 0.

strong_ref

Since there is no strong reference pointing to the object TestClass gets deallocated:

retain-cycle-image-2

By the way, if you take a look at the console, you can see that everything is working fine because the deinit method will only be called by the system when the instance gets deallocated.

If the instance of TestClass was not deallocated, there wouldn’t be the message “deinit”. As we will discuss later, placing a log message inside of deinit is a very good way to observe the deallocation of an object.

Retain Cycle Example

Now, we have two reference variables called testClass1, and testClass2.
testClass1 reference variable point to a newly allocated object TestClass.
testClass2 reference variable point to a newly allocated object TestClass.

the object pointed to by testClass1, has a property called next, which points a TestClass object. It then points to the object referenced by testClass2.

same applies to the object pointed to by testClass2.

Hence, so far each object has 2 strong references pointing to it.

The situation is visualized in the following picture:

retain-cycle-image-3

TestClass instance pointed to by testClass1, has ref count 2.
TestClass instance pointed to by testClass2, also has ref count 2.

ref_cycle

Now say we are done using these objects and we set our reference variables testClass1 and testClass2 to nil:

But the two instances won’t get deallocated! You can see this because there are not “deinit” messages in the console. Why is this happening? Let’s take a look at the situation:

retain-cycle-image-4

Each object has lost one strong reference, but because it is pointed to by the next property of each other, each object still has 1 strong reference pointing to it. Thus, both object still has +1.

This means these two objects won’t be deallocated. This is called a memory leak. If you have several leaks in your app, the memory usage of the app will increase every time you use the app. When the memory usage is to high, iOS will kill the app. That’s the reason why it’s so important to take care of retain cycles. So how can we prevent them?

Solution – using weak

Using so-called weak references is a way to avoid retain cycles. If you declare a reference as weak, it’s not a strong reference. Thus, by definition, a weak reference does not increment the reference count of an object. Only strong reference increment the count.

Let’s change our next property to weak, and see what happens:

From a reference count point of view:

weak_ref_cycle

Now, let’s set it to nil and see what happens.

Thus, now we set the reference to the objects to nil. This is -1 for the count. Due to weak having 0 effect on the reference count, the objects becomes 0 in reference count. Since the next property is weak, and we already niled the strong references testClass1 and testClass2, the two objects then becomes 0 reference count, and thus gets deallocated.

retain-cycle-image-5

Only weak references are left and the instances will be deallocated.

Because only optionals can become nil, every weak variable has to be an optional.

unowned

Besides weak, there is a second modifier that can be applied to a variable: unowned. It does the same as weak with one exception: The variable will not become nil and therefore the variable must not be an optional. It must be a non-optional variable.

But as I explained in the previous paragraph, the app will crash at runtime when you try to access the variable after its instance has been deallocated. That means, you should only use unowned when you are sure, that this variable will never be accessed after the corresponding instance has been deallocated.

Generally speaking it’s always safer to use weak. However, if you don’t want the variable to be weak AND you are sure that it can’t be accessed after the corresponding instance has been deallocated, you can use unowned.

It’s a little bit like using implicitly unwrapped optionals and try!: You can use them, but in almost all cases it’s not a good idea.

Common scenarios for retain cycles: delegates

retain-cycle-delegate

Essentially,

retain-cycle-image-6

retain-cycle-image-6b

So remember that you should in almost all cases declare delegates as weak to prevent retain cycles.

Here’s a look at the reference count perspective:

delegate_ref_cycle1

delegate_ref_cycle2

Retain cycles in closures

First, some semantics…

As a function parameter with explicit capture semantics:

As a function parameter with explicit capture semantics and inferred parameters / return type:

We can see in the logs that the instance of TestClass will not be deallocated. The problem is, that TestClass has a strong reference to the closure and the closure has a strong reference to TestClass:

You can solve this by capturing the self reference as weak:

In reference count perspective:

If we were to strong references, the object strongs the closure object, and the closure object strongs the TestClass object. Thus, when the object reference to TestClass gets pointed away, our TestClass still has +1 reference pointed to it by the closure.

block_cycle_1

If we are to use weak reference in the closure, TestClass object only has +1 reference count due to its instance reference. When we point away the instance reference, then it becomes 0, and thus everything gets deallocated, including its reference to the closure.

block_cycle_2

Local reference to closures

However, there won’t always be a retain cycle when using closures! For example, if you are just locally using the block, there is no need to capture self a weak:

The reason is that variable aBlock is created and pushed onto the local stack. Yes, it strongs the closure object. But when the local stack goes out of scope every local variable gets popped (including the strong reference to the closure). Thus, when it gets popped, all you’re left with is the closure object in the heap, with its strong reference back to TestClass so that it can use it.

Then once the closure object finishes executing, it sees that nothing is referencing it. Thus it gets deallocated, including its strong reference to TestClass.

local_stack_ref_closure

The same holds true when use for example UIView.animateWithDuration:

The idea here is the same. Locally, we’re simply referencing UIView’s class function. And that class function references the closure object. Once our local stack gets popped, the strong reference to UIView’s class function gets niled.

a child class should not have a strong reference to the parent class