Monthly Archives: March 2017

Enum in swift

https://appventure.me/2015/10/17/advanced-practical-enum-examples/
http://brettbukowski.github.io/SwiftExamples/examples/enums/

Basics

When creating an enum for use, make sure you declare public. Whatever name labels
you declare do not implicitly map to values. Rather, they are their own values.
When a variable is assigned to an enum’s member, and gets printed, it will literally
print the the enum member.

Say we assign a variable to enum’s C.

..and you print out the enum:

output:
C Tats Maksen Bukaku!

It prints C because we assigned our var to Example.C

Assigning other types to your enum values

When you print it, you will literally get the enum value, and its type.

output:
Str(“hehe”)

Also, nil cannot be assigned (or initialized) to Example.

Raw Values

Raw values are compile-time set values directly assigned to every case within an enumeration, as in the example detailed below:

In the above example code, case “A” was explicitly assigned a raw value integer of 1, while cases “B” and “C” were implicitly assigned raw value integers of 2 and 3, respectively.

To Raw Values

given…

We can declare enum of certain type. This means that the enum values can contain Strings, Ints…etc.
Here, we have a enum that contains Strings. Even though we can simply use the enum values, those enum values also have raw values, which are the strings that we assign them to.

For example, here, have a whole bunch of enum values, they are enough and can be used. However, they also have String values attached to them.
In order to get the string values, you can use rawValue of the enum value.

From Raw Values

You can also declare the enum with the raw value, and try to get the enum value back.
The enum value returned is an Optional type.

skill contains the enum value name ‘GuileMove’, which is an Optional Type
skill has 2 properties: hashValue, and rawValue.

Associated Values

Associated values allow you to store values of other types alongside case values, as demonstrated below:

Other Examples

Enum conform to Protocol

implement function description.

Other examples

Multiple cases, one code block

Throwing Errors in swift 3

ref – http://www.techotopia.com/index.php/Understanding_Error_Handling_in_Swift_2

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Representing and Throwing Errors

In Swift, errors are represented by values of types that conform to the Error protocol. This empty protocol indicates that a type can be used for error handling.

Handling Errors

When an error is thrown, some surrounding piece of code must be responsible for handling the error—for example, by correcting the problem, trying an alternative approach, or informing the user of the failure.

There are four ways to handle errors in Swift:
– You can propagate the error from a function to the code that calls that function
– handle the error using a do-catch statement
– handle the error as an optional value
– or assert that the error will not occur.

Propagate the error from a function to the code that calls that function

A throwing function propagates errors that are thrown inside of it to the scope from which it’s called.
hence, say our function fileTransfer throws an error.

We are call a throwing function with try phrase inside a do/try, where the catch code catches any errors thrown from the do function.

Only throwing functions can propagate errors. Any errors thrown inside a nonthrowing function must be handled inside the function.

example:

by default, in order to run the throw catch mechanism in order to handle the error, we use do-catch statement.

Full SOURCE CODE

OUTPUT:

—— fileTransfer function ———
fileTransfer – THROW NO CONNECTION!
clean THIS up! 😀
clean THAT up! 😀
CAUGHT —– NO CONNECTION!——
DONE!

Notice how our file transfer function runs first. Then right before it throws, it will call the defer functions.

After the defer functions are done executing, the exception is thrown and consequently, caught.

External and local names

https://useyourloaf.com/blog/swift-named-parameters/

Local parameter names are used in the body of the function/method
External parameter names are used when calling the function/method.

The external names for all except the first parameter default to the local name

When we call myFunc, we’d do it like:

As you can see, when calling the function, we use the param names userName. However, for 2nd parameter and on, the external name is the same as local name.

You omit the name of the first parameter when calling the function/method (since it does not by default have an external name)

Using External Names

If you rather define your own external names, and not use the local names, you can do so also. Just define your external name in front of the local name

Our three parameters now have these external and local names:

external: message, local: message
external: withPrefix, local: prefix
external: andSuffix, local: suffix

The use of external parameter names can allow a function to be called in an expressive, sentence-like manner, while still providing a function body that is readable and clear in intent.

Optional Binding

The constant variable songName is non-optional. It is valid only in the if block iff favoriteSong has valid data.
The non-optional songName cannot be used elsewhere.

Typealias in swift

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

TODO

Developers use typealias to create a new type identifier that’s a synonym for another type.

You can use typealias for most any type: classes, enums, structs, tuples, closures, etc.

For example:

JWT is basically a base64 encoded string of JSON.

Clients don’t need to verify the JWT in order to use them, and in fact when Orta and I began using them, we treated them only as strings retrieved from one API and sent to another (like an access token). However, instead of using the String type, I decided to define a JWT type alias.

I used the new JWT type throughout the code as a hint to other developers about what kind of string it is. This gave it some semantic meaning on top of being a string. Neat. Only later, when we needed to start decoding the JWT itself did this really come in handy.

if optionals are nil, and you do Optional Chaining

Optionals

Optionals are variables that have valid data OR nil.

For example a Non-optional variable is declared like so, and you must initialize it. If you do not initialize it, and you access it, then you’ll get an error:

But if you declare it as an Optional, then it will display nil

For string types, you can assign it an empty string, and call String functions on it:

We use ? to apply Optional Chaining.

Optional chaining lets you safely unwrap this value by placing a question mark (?), instead, after the property, and is a way of querying properties and methods on an optional that might contain nil.

example:

Say you have an optional variable that is initialized to nil.

If you decide to use optional chaining on that nil like the example below, it will send a message to execute function append with a String parameter. Once it sees that the object missingName is nil, it simply won’t do anything. This stays consistent with the original Objective-C language, where if you send a message to nil, nothing will happen.

However, if you were to use exclamation mark (“!”), which Force UnWrapping, it means you are sure the variable is NOT nil. If its nil, then the program will crash like so:

If you were to access the courses property through an exclamation mark (!) , you would end up with a runtime error because it has not been initialized yet.

Assign closure to var

ref – http://stackoverflow.com/questions/36749231/function-produces-expected-type-string-did-you-mean-to-call-it-with

There are two ways to assign closure to variable

First way, is very forward. You create a variable to be of type closure. This closure, let’s say, takes no parameter, and returns a String.
You assign it that variable and define the closure implementation. Then you execute the closure with “()”.

Second way, is a bit different. You define the closure definition, then call it in one move by using the “()”. Then you assign the resulting value to the variable hello2. Just make sure the variable type and the closure definition’s return type matches.

Defined as part of a class, using self

In a class, when you assign a closure to a property variable, you may want to use self in the closure implementation.

1) Use lazy – This is because as part of the process of the class initialization, self is not ready yet, thus, if you were to create a property, and define a closure
definition, you cannot use self. The only way to use self, is if you apply lazy to indicate that the property will be executed later in time when it is ready to be used, and this definitely happens after the initialization. This means that self is ready, and thus you can use it. Note that lazy means the closure is defined and assigned at a later time after when it needs to be used.

2) Usage of self – When you use self, you can use unowned or weak. Weak means it is optional, and thus, you must use the ? symbol to apply chaining access if you want to use its properties. When its unowned, it means its non-optional. Thus, you can just access as is.

3) Closure variable type – you must specify the closure’s type right after the variable, then assign it to the closure definition, like so:

You now have a variable of closure type, and can be executed multiple times later simply by using “()” after the closure variable name.

Execute Once
You can also declare a normal variable with a type, and take on the result of a closure once. In this case, you must define the closure definition and
execute it by using “()” in one step. Then you have it return the result back to the variable.

Notice the parameter list of the closure. If you want to add a self to use in the closure definition, just use brackets around your weak/unowned self
and put it in front of the closure parameters.

If you have parameters, make sure you pass them in.

Solution

Usage:

using weak/unowned self in property closure when there is an init function

ref – http://stackoverflow.com/questions/39560860/uiview-cmdevicemotionhandler-unowned-may-only-be-applied-to-class-and-class-b

self_in_closure_without_init

The line of code you’re on is actually run during the init function. self is not available until after all stored properties are initialized. You’re in the middle of the process.

The closure businessCardName we’re defining is in the middle of the init process, and thus, do not exist yet.

Solution:

Declare it indeed as lazy var instead of let, so the code is not run during init but in fact at first use.

Closure Solution

used like this:

its a closure, so to use it, we have to use the parentheses.

Using Anonymous Functions (also closures)

You can also use anonymous functions, execute it by using “()”, then assign the result back to variable.

used like this: