All posts by admin

Strong, weak, unowned

https://krakendev.io/blog/weak-and-unowned-references-in-swift

TODO! this article is NOT DONE

STRONG, and reference hierarchies

Let’s start off with what a strong reference is. It’s essentially a normal reference (pointer and all), but it’s special in it’s own right in that it protects the referred object from getting deallocated by ARC by increasing it’s retain count by 1. In essence, as long as anything has a strong reference to an object, it will not be deallocated. This is important to remember for later when I explain retain cycles and stuff.

Strong references are used almost everywhere in Swift. In fact, the declaration of a property is strong by default! Generally, we are safe to use strong references when the hierarchy relationships of objects are linear. When a hierarchy of strong references flow from parent to child, then it’s always ok to use strong references.

Here is an example of strong references at play.

Here we have a linear hierarchy at play. Kraken has a strong reference to a Tentacle instance which has a strong reference to a Sucker instance. The flow goes from Parent (Kraken) all the way down to child (Sucker). There is no retain cycle.

Closure as parent

Usually when you use static functions (via class, or from singletons), the closure references another object (usually the self).

Since animateWithDuration is a static method on UIView, the closure here is the parent and self is the child.

Closure as child – Retain cycle

A retain cycle is what happens when two objects both have strong references to each other. If 2 objects have strong references to each other, ARC will not generate the appropriate release message code on each instance since they are keeping each other alive.

If any variable is declared outside of the closure’s scope, referencing that variable inside the closure’s scope creates another strong reference to that object. The only exceptions to this are variables that use value semantics such as Ints, Strings, Arrays, and Dictionaries in Swift.

Here, NSNotificationCenter retains a closure that captures self strongly when you call eatHuman(). Best practice says that you clear out notification observers in the deinit function. The problem here is that we don’t clear out the block until deinit, but deinit won’t ever be called by ARC because the closure has a strong reference to the Kraken instance!

kraken-closure

How to fix? Introducting…

The fix is to use a weak reference to self in the closure’s capture list. This breaks the strong reference cycle.

Generally speaking…

You can specify multiple capture values in a closure!

WEAK in detail

A weak reference is just a pointer to an object that doesn’t protect the object from being deallocated by ARC. While strong references increase the retain count of an object by 1, weak references do not. In addition, weak references zero out the pointer to your object when it successfully deallocates. This ensures that when you access a weak reference, it will either be a valid object, or nil.

In Swift, all weak references are non-constant Optionals (think var vs. let) because the reference can and will be mutated to nil when there is no longer anything holding a strong reference to it.

For example, this won’t compile:

because tentacle is a let constant. “Let constants” by definition cannot be mutated at runtime. Since weak variables can be nil if nobody holds a strong reference to them, the Swift compiler requires you to have weak variables as vars.

weak-let

Delegate weak

Given,

When you create delegate definition, and then subsequently use them, make sure you mark them as weak.
Here’s why. Say we have instance Kraken. Kraken strongs an instance tentacle. Then Kraken instance makes tentacle
instance’s delegate point to self. Thus, we now have a retain cycle. Kraken strongs tentacle. Tentacle’s strong property
‘delegate’ strongs Kraken.

In order to fix this, make sure the delegate is marked as weak. Also, in order to use weak,
make sure your delegate extends class. This is because non class type protocols cannot be marked as weak.
Easy!…let’s just make it a class type protocol by extending it with :class:

UNOWNED

Weak and unowned references behave similarly but are NOT the same. Unowned references, like weak references,
do not increase the retain count of the object being referred.

However, in Swift, an unowned reference has the added benefit of
not being an Optional.

In addition, unowned references are non-zeroing. This means that when the object is deallocated, it does not zero out the pointer. This means that use of unowned references can, in some cases, lead to dangling pointers. For you nerds out there that remember the Objective-C days like I do, unowned references map to unsafe_unretained references.

Use a weak reference whenever it is valid for that reference to become nil at some point during its lifetime. Conversely, use an unowned reference when you know that the reference will never be nil once it has been set during initialization.

“Define a capture in a closure as an unowned reference when the closure and the instance it captures will always refer to each other, and will always be deallocated at the same time.”

If you know your reference is going to be zeroed out properly and your 2 references are MUTUALLY DEPENDENT on each other (one can’t live without the other), then you should prefer unowned over weak, since you aren’t going to want to have to deal with the overhead of your program trying to unnecessarily zero your reference pointers.

A really good place to use unowned references is when using self in closure properties that are lazily defined like so:

We need unowned self here to prevent a retain cycle. Kraken holds on to the businessCardName closure for it’s lifetime and the businessCardName closure holds on to the Kraken for it’s lifetime. They are mutually dependent, so they will always be deallocated at the same time. Therefore, it satisfies the rules for using unowned!

HOWEVER, this is not to be confused with lazy variables that AREN’T closures such as this:

Unowned self is not needed since nothing actually retains the closure that’s called by the lazy variable. The variable simply assigns itself the result of the closure and deallocates the closure (and decrements the captured self’s reference count) immediately after it’s first use.

Unit Testing in xcode

ref – https://x-team.com/blog/how-to-get-started-with-ios-unit-tests-in-swift/

Create a Mac OS X project

File > New > Project

Under macOS, select Command Line Tool. Name it UnitTestTutorial.

Then create a MyMath class and enter some functions for adding and multiplying.

File -> New -> File, and then under macOS, select Unit Test Case Class. If you are doing an iOS project, make sure you are under the iOS tab.
Name it MyMathTests.

You will then see a MyMathTests folder appear and see the MyMathTests.swift file.

unit-test-folder-xcode

Open the file and you’ll see something like this:

Writing test cases using XCTAssert

What we’ll do is to add code to testExample in order to run those tests.

Specifcically, XCTAssert is the starting name convention for a whole slew of test functions that you can use. Type in
XCTAssert, and a whole list of functions should appear at your disposal. You can test for truth, false, equals, Less Than, Nil, etc.

Basically, just follow the parameters and insert your functionality. There is usually a string parameter for you to put in case it fails.

output:

Test Suite ‘MyMathTests’ started at 2017-03-23 11:13:24.083
Test Case ‘-[MyMathTests.MyMathTests testExample]’ started.
/Users/rickytsao/Desktop/UnitTestTutorial/MyMathTests/MyMathTests.swift:29: error: -[MyMathTests.MyMathTests testExample] : XCTAssertLessThan failed: (“20”) is not less than (“12”) – Uh oh! Less Than testing failed
/Users/rickytsao/Desktop/UnitTestTutorial/MyMathTests/MyMathTests.swift:33: error: -[MyMathTests.MyMathTests testExample] : XCTAssertEqual failed: (“4”) is not equal to (“2”) – UH OH! FAILED!
Test Case ‘-[MyMathTests.MyMathTests testExample]’ failed (0.085 seconds).
Test Suite ‘MyMathTests’ failed at 2017-03-23 11:13:24.169.
Executed 1 test, with 2 failures (0 unexpected) in 0.085 (0.086) seconds
Test Suite ‘MyMathTests.xctest’ failed at 2017-03-23 11:13:24.169.
Executed 1 test, with 2 failures (0 unexpected) in 0.085 (0.087) seconds
Test Suite ‘Selected tests’ failed at 2017-03-23 11:13:24.170.
Executed 1 test, with 2 failures (0 unexpected) in 0.085 (0.088) seconds

Test session log:
/Users/rickytsao/Library/Developer/Xcode/DerivedData/UnitTestTutorial-aqmgqblqbwnvegfxiosuphlxvvyt/Logs/Test/54D591AF-874C-46FA-9840-4996047E7F05/Session-MyMathTests-2017-03-23_111319-FnoV9M.log

Non-parameter closures are @escaping by default

http://stackoverflow.com/questions/40072918/how-to-call-non-escaping-closure-inside-a-local-closure

Non-parameter closures are @escaping, by default

non-parameter closures in Swift 3.0

Given the example:

localClosure’s closure is @escaping which naturally means it cannot be allowed to wrap the non-escaping closure parameter “closure” of test(…).

Thus, the solution is that we may naturally mark closure as @escaping if we’d wish to process/wrap it as in the example.

How to open Parent App from iMessage extension

ref – http://stackoverflow.com/questions/24297273/openurl-not-work-in-action-extension

xcode 8.2.1, ios 10.2, swift 3

File > New > Project > Create Single App

Then, click on your project (blue project icon):

File > New > Target > iMessage Extension

Parent App

AppDelegate

iMessage Extension

Throw a button in your xib, and to a handler like so:

If you’re not in UIViewController, you can go:

swift initializer

http://stackoverflow.com/questions/30896231/why-convenience-keyword-is-even-needed-in-swift
http://stackoverflow.com/questions/25126295/class-does-not-implement-its-superclasss-required-members/32108404#32108404

Designated Initializers and Convenience Initializers in Swift


https://theswiftdev.com/2015/08/05/swift-init-patterns/

http://www.codingricky.com/construtor-chaining-in-swift/

Initializers fall into two categories, Designated and Convenience.

Designated Initializers

Designated initializers are the primary initializers and are responsible for initializing all properties of a class. So in this case, the only initializer here is known as the Designated one.

Now if you want to add other initializers to make use of the Designated one, they will be known as Convenience initializers. So let’s add one that defaults the age. Convenience initializers have the keyword convenience before them.

Convenience initializers need to delegate to another Convenience initializer or a Designated initializer.

Here’s an example of a Convenience initializer calling another Convenience one.

Two Designated initializers, Two Convenience initializers

What about subclasses?

Once again, with initializers, there are certain rules that need to be adhered to when subclassing. So Designated initializers must call other Designated initializers in their immediate parent class.

So let’s take a look at an example. We are adding a Student class as a subclass of the Person class. It will add a property student number.

Here we are calling the Designated initializer in the Person class. If we tried to call one of the Convenience initializers in the Person class, a compile error would occur. Also note, we need to assign the number property before calling the initializer in the parent class as it is a requirement to ensure all properties are initialized in child classes before their respective parent initializer is called.

Designated initializers delegate up and Convenience initializers delegate across.

ref – https://theswiftdev.com/2015/08/05/swift-init-patterns/

NSObject subclass init

If you subclass NSObject you can go on multiple “roads”

Example 1 – inits are designated.

Whether you want to over-ride NSObject’s init, or create your own init, YOU MUST use super.init() at the very end. This
signifies that after initializing all of your properties, you finally call the parent’s (NSObject) designated init.

Also, if you declare a function interface that is the same as the parent, you are overriding it, and must use the override
keyword.

Essentially, when we override a parent’s function, we must 2 things:
1) make sure the function interface is the same
2) init self property, and then call the parent’s over-ridden function

If you want to continue to subclass Apple, you can, but the main rule is that the designated init (super.init(..)) must always
be called in the very end.

Convenience

Before, when we override a parent’s function, we must do 2 things:

1) make sure the function interface is the same
2) init own property, and then call the parent’s over-ridden function

Now, we do step 2) differently. We can call our own designated init function instead.

We can use convenience in overriding parent functions, or we can use it in our own designated initializers.
Notice that the convenience init calls the designated init.

UIViewController subclass init

We are required to implement the protocol function init(coder aDecoder: NSCoder). Hence, we use a convenience function on a designated init with a NSCoder parameter.

Custom UIView

So in our custom view, we first create a initialize function that initializes self properties.
This initialize function will be called AFTER in every init functions.

In example //1, we over-ride parent’s interface init(frame: CGRect). We call the parent’s init function to make sure initialization goes through smoothly.
Then, we finally initialize our own properties.

Create custom UIView from XIB

we convenience the required protocol function to call our own designated init function. In that init function,
we set up own property, then call parent’s protocol required init function if coder is valid.
If not, we simply call parent’s designated function.

Init Singletons

Use a static variable to signify that this class only has one instance of this type. Then we simply over-ride
the parent’s init function with our own init. When over-riding, make sure to call the parent’s function first.

Required Initializers

A required initializer is a required function of a protocol. When a class conforms to that protocol, the required initializer function makes a guarantee that you can initialize the class type (or any of its sub types) with that initializer.

In other words, if you have an initializer function in a protocol and you conform a class to that protocol, you have to use required (if it’s a class) because that protocol guarantees that the initializer is present on that class, and any of its subclasses.

When you use required on an initializer of a class, that signals that all of its subclasses can also be initializer using that method. This means you also need to add that initializer to any of its subclasses.

Say a protocol defines an init function. This means whatever class that conforms to TestProtocol is “required” to implement it.

Thus, if we have a TestClass that conforms to TestProtocol, we must use required.

In other words, the required keyword must be present because any subclasses of TestClass must also provide init() (because they also conform to TestProtocol) .

Note that the keyword required is only allowed on “init” declarations
required_only_used_for_init

Having a required initializer allows you to initialize a class without knowing what it is at compile time, which is useful for a variety of reasons:

Required initializers and designated initializers are not really related, though the associated keywords required and convenience are both used to specify restrictions on subclasses.

Having a required initialiser allows you to initialise a class without knowing what it is at compile time, which is useful for a variety of reasons. We take on the object TestClass.self and put it into constant variable classType. Then we assign it to constant variable object, and then just call the init of that class type.

If your class conformed to multiple protocols, each with a different initializer for example, each of those initializers must also be required. For example, in the below example, we must conform to superclass TestClass’s protocol TestProtocol’s init method.
Then, since we conform to OtherProtocol, we must implement its required init method also.

You can implement a required initializer on a class by initializing a type of a class which isn’t known at compile time. This is great for when you loop through an array, and there is a lot of subclass objects, and you don’t know which type is going to be used.
For example, say we have base class Animal. And its subclasses are Horse, Tiger, Giraffe. You want to go through that array, and call an init on them. Problem is, you don’t know what animal is in each array’s element.

So all you have to do is initialize the base class type “Animal” as temporary variable, and simply point to all the subclass animals.
Then just call init on the base class type “Animal”, which will then return the subclass animal instance.

Designated Initializers

Like most constructs in Swift, designated initializers are aptly named and do exactly what they say they do. They are the main initializers to be used for a class. A class must have one designated initializer, but it is not limited to one. It can have multiple if necessary, but most classes only have one.

To create a designated initializer, it is just the init keyword, with the parameters afterwards, and then the code inside the curly braces. Designated initializers tend to set all of the properties up and let the user send in values for each.

Let’s take a look at a designated initializer:

In other words, a designated initializer is one which isn’t a convenience initializer (i.e, marked with convenience).

A designated initializer must make sure that all properties of the class have a value before the initializer finishes (or a super initializer is called). Convenience initializer only don’t have this requirement because they must themselves call a designated initializer.

Convenience Initializers

A convenience initializer often has some of those hard coded, and thus can take less parameters. The developer usually write’s a convenience initializer to set some defaults that are appropriate to a special use case.

The main difference in their syntax, is that convenience initializers have the convenience keyword before the init. Otherwise they are exactly the same. Once inside our convenience initializer that only takes the sender as a parameter, we just give that parameter to the designated initializer as both the sender and the recipient, since this Message is being used more like a note.

Rules for Designated and Convenience Initializers

A Swift class must initialize its own (non-inherited) properties before it calls its superclass’s designated initializer.

Swift has three rules as to how designated and convenience initializers relate to each other. Instead of trying to paraphrase them, I’m just going to quote Apple’s iBook directly:

  • A designated initializer must call a designated initializer from its immediate superclass.
  • A convenience initializer must call another initializer from the same class.
  • In rule 2, you see that it just says that a convenience initializer must call another initializer. It doesn’t say dedicated initializer there, just any initializer. If you want, you can have several convenience initializers that handle a small part of the initialization, and just call them in a chain

  • A convenience initializer must ultimately call a designated initializer.

Unlike subclasses in Objective-C, Swift subclasses do not inherit
their superclass initializers by default.

for example, if you were to subclass NSObject, and in your current class’s code you go

If you do not write your own init, it would execute NSObject’s init
in swift, if you were to call init(), (and assuming you did not implement it), it would not go anywhere. It is undefined

if this was objc, it would inherit Foo’s initializer, which then would then auto-initialize Bar’s bar property to nil

however, in swift, bar is an NON-OPTIONAL, which means it must contain a value, and can never be nil.

Ultimately, it all boils down to the basic understanding that Swift’s initializers play by a slightly different set of inheritance rules which means you’re not guaranteed to inherit initializers from your superclass. This happens because superclass initializers can’t know about your new stored properties and they couldn’t instantiate your object into a valid state

UITapGestureRecognizer

Project sample

swift 3

objective
the delegate

optional – handler

functions, closures, completion handler

demo (swift 3, xcode 8.2)

swift string specifier

http://stackoverflow.com/questions/25339936/swift-double-to-string

var a:Double = 1.5
var b:String = String(format:”%f”, a)
print(“b: \(b)”) // b: 1.500000
With a different format:

var c:String = String(format:”%.1f”, a)
print(“c: \(c)”) // c: 1.5

Objective-C API returns implicit wrapped optional

ref – http://stackoverflow.com/questions/24728235/why-do-objective-c-apis-return-implicitly-unwrapped-optionals

When you make an implicitly unwrapped optional in Swift, it does not mean that it is always going to be non-nil:

all it means is that you tell the compiler that when you access their properties, you expect the object to be non-nil.

The object that you reference can be explicitly checked for nil:

setting it to nil will not cause an exception either, unless you try to access any of its properties after that.

When Apple used implicitly unwrapped optionals for the parameters of

they let you save on a few extra if – let by using UITableView!

That way, all you have to do is go:

If you consider an alternative of making the parameters UITableView? and NSIndexPath? instead, all implementations would have to either use an exclamation point after tableView and indexPath, or use the if – let idiom.

Compared to this choice, implicitly unwrapped types look like a better choice.

Therefore

It’s a tradeoff between absolute safety and convenience. Since it could potentially be nil it must be optional.

Implicitly-unwrapped makes it more convenient for you in the cases when you are sure that it’s not nil (and if you’re wrong, it throws an error), just like if you “force unwrapped” it everywhere.

If you are not sure it’s not nil, you can still use optional binding and optional chaining. So basically you the programmer can choose the appropriate way to use it. This way Apple doesn’t have to go through and explicitly annotate nullable/non-nullable in the whole API.