All posts by admin

Protocols in swift

http://stackoverflow.com/questions/24024466/how-do-i-make-a-class-conform-to-a-delegate-in-swift

Learn Swift from Objective-C : Protocols and Delegation

Defining a protocol

Conforming to protocol

Delegate it

To create a delegate in obj-c, it uses id to mean that this class can be of any type,
as long as it conforms to some protocol in the “<" ">” bracket. The variable name is delegate.

in swift, it is simply declaring an optional variable called delegate of type SampleProtocol.
That way, it can show that its valid or nil.

The variable is of any type by default.

Using your delegate

if you delegate is connected, using the protocol function will not be nil. If your delegate is not connected and is nil, then delegate?.YourFunc() will return nil

Optional protocol functions

http://stackoverflow.com/questions/24032754/how-to-define-optional-methods-in-swift-protocol

If you want to declare optional functions in your protocol, you must declare @obj keyword in your protocol declaration. You must ALSO declare @obj keyword in front of your optional function

Remember to declare the required protocol functions in your class. If not, you’ll get a compiler error to remind you to do so:

swift_required_protocol_function

Object type of the delegate

Swift’s var is not Objective-C’s id

In swift, a variable can be of any type. Its type is set when you assign it to an object.
Thus, in swift, you do not need to specify id, as you did in objective c.

Swift’s var vs Obj-C’s id

Swift is a statically typed language, so once a variable (var) is defined, the type of that variable will remain the same forever. With id in Objective-C, that’s not necessarily the case.

In Swift, once a variable is defined, you can’t change its type. However, an obj-c id can switch around.

This illustrates the difference between Swift and Objective-C, or in a more general sense, the difference between statically typed and dynamically typed languages.

Let’s look at the definition of those words: “static” and “dynamic”. Starting with “static”, courtesy of the Dictionary in OS X:

“lacking in movement, action, or change”
So if calling something static means that it lacks movement, action, or change, then saying a language is statically typed means that its types cannot change. And that’s what we have in Swift.

Contrast this with “dynamic”:

“characterized by constant change, activity, or progress”
Sounds a bit like Objective-C’s id type, right? Its type is contantly changing, or at least, it can be changed constantly, as we did in the example above.

“But wait,” you may be thinking, “Swift’s var is constantly changing, too – it’s just like Objective-C’s id.” And you’re half-right – we can do the following in Swift:

So it looks like var is constantly changing – sometimes it represents an Int, sometimes a String. But the type of the variable never changes – our a is always an Int, and our b is always a String. And remember our previous example, where we tried to change x from 1 to “hello” and the compiler screamed at us. Once a variable’s type is set in Swift, it’s set. It can’t change. And that’s what static typing is.

So that brings us to another question: how is a variable’s type set in Swift? Let’s look at our previous Swift example again:

The error from the compiler (on line 2 above) gives us the type. The error says (in Xcode 6 Beta 4):

Type ‘Int’ does not conform to protocol ‘StringLiteralConvertible’
So we can conclude that Swift has inferred the type of x – it’s an Int, and we didn’t call it one. This is known as type inference, and it’s one nice feature in Swift that’s not in Objective-C.

Let’s look at the definition of the word “infer”:

“deduce or conclude (information) from evidence and reasoning rather than from explicit statements”
Swift uses type inference to conclude that our little x is of type Int, even though we didn’t explicitly state that x should be an Int. And then it prevents us from changing x to a String since Swift is statically typed. This is in stark contrast to Objcetive-C, which requires explicit types and is dynamically typed.

Swift’s var is decidedly not Objective-C’s id – it’s just a keyword we use to state that we’re creating a variable. That variable’s type is inferred by the compiler via a feature called type inference, and once that variable has a type, it always has that type. Once an Int, always an Int.

In Swift 3, the id type in Objective-C now maps to the Any type in Swift, which describes a value of any type, whether a class, enum, struct, or any other Swift type.

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!

git commands

https://tortoisegit.org/docs/tortoisegit/tgit-dug-conflicts.html

Switch Branch

> git checkout -b

Show origin of current git directory

> git remote show origin

* remote origin
Fetch URL: https://ricky_tsao@gitcn.epam.com:4443/ricky_tsao/joiner-app-backend.git
Push URL: https://ricky_tsao@gitcn.epam.com:4443/ricky_tsao/joiner-app-backend.git
HEAD branch: master
Remote branch:
master tracked
Local branch configured for ‘git pull’:
master merges with remote master
Local ref configured for ‘git push’:
master pushes to master (up to date)

Resolving Conflicts

During a merge, the working tree files are updated to reflect the result of the merge. Once in a while, you will get a conflict when you merge another branch, cherry-pick commits, rebase or apply a stash: Among the changes made to the common ancestor’s version, non-overlapping ones (that is, you changed an area of the file while the other side left that area intact, or vice versa) are incorporated in the final result verbatim. When both sides made changes to the same area, however, Git cannot randomly pick one side over the other, and asks you to resolve it by leaving what both sides did to that area. Whenever a conflict is reported you need to resolve it!

The conflicting area is marked in the file like this (also cf. the section called “HOW CONFLICTS ARE PRESENTED”):

The code from your current branch is on top, the code from the branch you are merging in is on the bottom

The contents after the first marker originate from your current working branch. After the angle brackets, Git tells us where (from which branch) the changes came from. A line with “=======” separates the two conflicting changes.

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.)