All posts by admin

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

iMessage test app

ref – http://stackoverflow.com/questions/39419854/xcode-8-code-signing-error

When you run a iMessage default app, you will notice three icons next to the text message text field. A camera, digital draw, and the iMessage app icon.

Once you touch the iMsg app icon, it will bring up a list of iMsg apps. You will see your app testMessage like so:

imsg_app

Once you select your app, you’ll see it being run. You will see the “Hello World” label, along with the name of your app.

imsg_short

Then, once you click on the arrow button on the bottom right, you make the iMsg app run full mode

imsg_full

inout parameters

ref – http://stackoverflow.com/questions/34486052/when-to-use-inout-parameters/34486250

inout means that modifying the local variable will also modify the passed-in parameters.
Without it, the passed-in parameters will remain the same value.
Trying to think of reference type when you are using inout and value type without using it.

You’ll see that when we use functions with inout parameter, we pass in address of the objects using ampersand (&).
This is because inout uses address of the incoming object. That way, when we make changes inside the function, it dereferences
the address of the object. This means it gets the value of the object at the address passed in, and when we make changes, THAT change
is permanent.

By default, function parameters are declared let. This makes it constant, and does not allow you to change the values. You can simply use them inside the function.

Function parameters are constants by default

Trying to change the value of a function parameter from within the body of that function results in a compile-time error. This means that you can’t change the value of a parameter by mistake.

As of Swift 3.0, you only have 2 choices. Use the default behavior where your variable parameters is let. Or use inout where it is used like a reference.

http://stackoverflow.com/questions/34400600/using-inout-keyword-is-the-parameter-passed-by-reference-or-by-copy-in-copy-out?noredirect=1&lq=1

As an optimization, when the argument is a value stored at a physical address in memory, the same memory location is used both inside and outside the function body. The optimized behavior is known as call by reference; it satisfies all of the requirements of the copy-in copy-out model while removing the overhead of copying. Do not depend on the behavioral differences between copy-in copy-out and call by reference.

Guard

Swift Guard Statement


https://thatthinginswift.com/guard-statement-swift/

The Pyramid Of Doom In Swift

WHY USE GUARD?

Let’s take a look at a simple example comparing the old techniques vs using the guard statement:

This is the most basic Objective-C style way to make sure a value exists and that it meets a condition.

Now this works fine, but has a couple flaws:

You’re checking for a condition that you don’t want, rather than checking for the value you do want.
Code becomes confusing when you have a bunch of checks like this. What you’re hoping for here is that your condition actually doesn’t pass.

You also need to force unwrap the optional value after the condition fails.

Swift gave us a way to clean this up and fix some of these flaws through Optional Binding:

1) We check for what we want
2) Do not need to force unwrap the optional. the tempX used inside the code block is unwrapped for you already.

This removes both of the flaws that the first function had.

The Swift Pyramid of Doom

However, it introduces a tiny problem. You might not immediately see a problem with this, but you could imagine how confusing it could become if it was nested with numerous conditions that all needed to be met before running your statements.

For example:

You’re putting your desired code within all the conditions, rather than afterward. This is a problem when you have numerous conditions that need to be met before running what you want. Conceptually, the way to fix this is to do your checks first. If any of the checks do not hold, we exit. Thus, this lets you run the code you want AFTER all the checks are satisfied. In other words, do each of your checks first, and exit if any aren’t met. This allows easy understanding of what conditions will make this function exit.

Its kinda like having a guarding your club. You only want non-smoking, long haired, and female patrons in your club. So your bouncer checks if the person is a non-smoker. Yes. Ok, next does the person have long hair? Yes. Is the person female? Yes. Okay, the patron gets to go into your club. In our case, the variable checks through and gets executed by your code below.

If any of the traits are not met, the bouncer will throw that person out. In our case, the code returns.

You want to get rid of the bad cases before they get in the door.

Solution is to use guard:

Solution: the guard statement

Using guard solves all 3 of the issues mentioned above:

  • Checking for the condition you do want.

    If the condition is not met, guard‘s else statement is run, which breaks out of the function.
  • If the condition passes, the optional variable here is automatically unwrapped for you within the scope that the guard statement was called (in this case, the fooGuard(_:) function). Thus, validX is the unwrapped variable for you to use.
  • You are checking for bad cases early, making your function more readable and easier to maintain.

Even if your variable is non-optional, you can also use guard

Value types vs Reference Types

ref – https://developer.apple.com/swift/blog/?id=10

Value and Reference Types

Types in Swift fall into one of two categories: first, value types, where each instance keeps a unique copy of its data, usually defined as a struct, enum, or tuple.

The second, reference types, where instances share a single copy of the data, and the type is usually defined as a class.

What’s the Difference?

The most basic distinguishing feature of a value type is that copying — the effect of assignment, initialization, and argument passing — creates an independent instance with its own unique copy of its data:

Copying a reference, on the other hand, implicitly creates a shared instance. After the reference copy, two variables then refer to a single instance of the data, so modifying data in the second variable also affects the original, e.g.:

The Role of Mutation in Safety

One of the primary reasons to choose value types over reference types is the ability to more easily reason about your code.

If you always get a unique, copied instance, you can trust that no other part of your app is changing the data under the covers.

This is especially helpful in multi-threaded environments where a different thread could alter your data out from under you.
This can create nasty bugs that are extremely hard to debug.

Because the difference is defined in terms of what happens when you change data, there’s one case where value and reference types overlap: when instances have no writable data. In the absence of mutation, values and references act exactly the same way.

You may be thinking that it could be valuable, then, to have a case where a class is completely immutable. This would make it easier to use Cocoa NSObject objects, while maintaining the benefits of value semantics. Today, you can write an immutable class in Swift by using only immutable stored properties and avoiding exposing any APIs that can modify state. In fact, many common Cocoa classes, such as NSURL, are designed as immutable classes.

However, Swift does not currently provide any language mechanism to enforce class immutability (e.g. on subclasses) the way it enforces immutability for struct and enum.

How to Choose?

So if you want to build a new type, how do you decide which kind to make?

Use a value type when:

  • Comparing instance data with == makes sense
  • You want copies to have independent state
  • The data will be used in code across multiple threads

Use a reference type (e.g. use a class) when:

  • Comparing instance identity with === makes sense
  • You want to create shared, mutable state

In Swift, Array, String, and Dictionary are all value types.

They behave much like a simple int value in C, acting as a unique instance of that data. You don’t need to do anything special — such as making an explicit copy — to prevent other code from modifying that data behind your back. Importantly, you can safely pass copies of values across threads without synchronization. In the spirit of improving safety, this model will help you write more predictable code in Swift.

swift 3 – accessors

https://stackoverflow.com/questions/41741955/in-swift-what-is-the-difference-between-the-access-modifiers-internal-and-publi

open means classes and class members can be subclassed and overridden both within and outside the defining module (target).
In other words, an open class is accessible and subclassable outside of the defining module. An open class member is accessible and overridable outside of the defining module.

fileprivate restricts the use of an entity to its defining source file. Basically accessible by multiple classes within a single file.

private restricts the use of an entity to its enclosing declaration.

internal enables an entity to be used within the defining module (target). Also, this happens to be the default specifier if nothing else is mentioned. We would typically use internal access when defining an app’s or a framework’s internal structure.

swift 3 – properties

ref –
https://developer.apple.com/library/content/documentation/Swift/Conceptual/Swift_Programming_Language/Properties.html
http://stackoverflow.com/questions/24018327/what-does-an-exclamation-mark-mean-in-the-swift-language
https://mikeash.com/pyblog/friday-qa-2014-06-20-interesting-swift-features.html

Declaring Properties

Implicit Optional type

The existence of NULL in C (nil in Objective-C) means that all pointer types in the language are implicitly optional types. If you have a NSString *, it means “pointer to NSString, or nil”. If you have a char *, it means “pointer to char, or NULL”.

The existence of NULL in C blows apart the entire static type system when it comes to pointers. Every pointer type is a half truth. Whenever you see a type “pointer to X”, there’s always an implied “…or NULL.”

Swift approaches this in a consistent manner by making all types non-optional, and allowing any type to be made optional with an additional annotation.

nonOptStr String is the default behavior that Swift wants to do.

optStr is the optional type that can contain either nil or the String in our case, and the additional annotation is the “?”.

Here, a is a plain Int and it always contains some integer value. b is an optional Int and it either contains an integer value, or it contains nothing.

If a parameter can accept nil, then it will be declared as an optional type. If it can’t, it won’t. The compiler can easily check your code to make sure it’s doing the right thing. Likewise, if a return value can be nil, it will be an optional type, making it obvious. In the common case, your types will be non-optional, making it clear that they always hold something.

Optional Binding

This is to safely display your optional value. If its nil, you can specify an error block.

However, if we do not set it, x is nil, and thus, our optional type

result:
uh oh, x is NOT VALID

Forced Unwrapping

Do forced unwrapping only if you are sure that the variable will not be nil.

If x is valid, we’d get a valid int result. However, if x is not set, we’d get runtime error.

forced_unwrapping

This language design forces the nil case to be handled explicitly, which improves safety over Obj-C

Classes/Structs and properties

A property declared with ‘var’ that belongs to a class is called a variable store property

A property declared with ‘let’ that belongs to a class is called a constant store property

Stored Properties of Constant Structure Instances

If you create an instance of a structure and assign that instance to a constant, you cannot modify the instance’s properties, even if they were declared as variable properties:

Notice that myStruct contains variable store property, which means it is mutable. However, the instance of myStruct “s1” is constant. Thus, it is not possible to change “description”, even though it is a variable property.

constant_data_type_error
This behavior is due to structures being value types.

When an instance of a value type is marked as a constant, so are all of its properties.

The same is not true for classes, which are reference types.

If you assign an instance of a reference type to a constant, you can still change that instance’s variable properties.

swift 3 – First parameter names

ref – http://stackoverflow.com/questions/38343497/swift-3-first-parameter-names

_ person

_ means the external parameter name is optional, as demonstrated below.
person is the local name, in which you use in the function body

use it like:

on day

on is the external name which is used when calling the function
day is the local name which is used inside the function name.