LiBenkuo / blog

用Issues写Blog
1 stars 0 forks source link

Swift #8

Open LiBenkuo opened 8 years ago

LiBenkuo commented 8 years ago

Closure

A closure is simply

a piece of source code that can pass around just like any other type of object.

The difference between a closure and regular source code is that

the code from the closure does not get perform right away.

It is stored in a "closure object" and can be performed at a later point, even more than once.

Just like a method or function, a closure can accept parameters.

They are separated from the source code by the "in" keyword.

Thanks to Swift's type inference you don't need to specify the data types of the parameters. However, you could write them out in full if you want to.

If a closure is the last parameter of a method, you can use trailing syntax to simplify the code a little.

Closures are useful for other things too, such as initializing objects and lazy loading.

It is no coincidence that closures look a lot like functions.

In Swift closures, methods and functions are really all the same thing.

For example, you can supply the name of a method or function when a closure is expected, as long as the parameters match.

That somewhat negates one of the prime benefits of closures - keeping all the code in the same place - but there are situations where this is quite useful (the method acts as a "mini" delegate.)

Closures capture any variables use inside it, including self.

This can create ownership cycles, often leading to memory leaks. To avoid this, you can supply a capture list.

Swift also has the concept of "no escape" closures.

LiBenkuo commented 8 years ago

if-let-where

When ever you need to unwrap an optional and also check the value of that optional, using if-let-where is the nicest way to do that.