Category Archives: Uncategorized

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.

Swift 3 classes

Classes

ref – https://code.tutsplus.com/tutorials/swift-from-scratch-an-introduction-to-classes-and-structures–cms-23197

go to full source

or download xCode proj here

Create a basic class:

First, we must create instance variables (ivars). The ivars are to be private because we do not want others to access.

Also, we use optional so it can have nil values.

We declare private as the accessor. Then use var, so that the ivar’s state can be changed.

Initializers

Initializers are called to create a new instance of a particular type. In its simplest form, an initializer is like an instance method with no parameters, written using the init keyword.

#function is a macro used to display the local scope’s function call name.
print is a function used to log strings to the console.
self is to reference the current instance working instance.

You can have overloaded functions, with different parameters.

Functions

This function is called toStringFromArray
Accessor is private
parameter name is data
parameter label is OfStrings
parameter is an array of type String as denoted by [String]
return value is String as denoted by -> String

We have a variable called total that is of type String. It is initialized to empty string literal.
We then use for in to loop through the array “data”. The temp variable “aString” used in the loop
it to denote the string value at each index. We add that string to our total string.

We basically append all the strings from the array data, into the string total. Then return it.

In order to use this function we go

We will be using toStringFromArray in another function like so.

function name is fullName
return type is String
accessor is private

It basically does optional binding to get the values of our instance variables.
then it calls our private function toStringFromArray in order to take an array, and
return a String variable with all the array’s string data int it.

Unwrapping Conditional

Now that we have the data we need from fullName function, and a instance variable,
we can unwrap conditional for the instance variable self.gender. Then place it together with fullName
to return the Person’s full information

Underscore _

underscores are used as the parameter label to denote that the label is optional

You can then call the function without denoting the parameter labels

Using just the parameter names, no label

You can also use just use the parameter name like so:

Full Source Code


Output:

Hello, World!
–> init(first:last:gender:)
<-- init(first:last:gender:) --> fullName()
<-- fullName() --> toStringFromArray(OfStrings:)
<-- toStringFromArray(OfStrings:) The full name is: Ricky Tsao , Male --> init(first:last:)
<-- init(first:last:) The full name is: Sorry, data is incomplete Program ended with exit code: 0

Swift 3.0 – Mutating

Modifying Value Types from Within Instance Methods

Structures and enumerations are value types. By default, the properties of a value type cannot be modified from within its instance methods.

However, 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:

// Prints “The point is now at (3.0, 4.0)”

The Point structure above defines a mutating moveBy(x:y:) method, which moves a Point instance by a certain amount. Instead of returning a new point, this method actually modifies the point on which it is called. The mutating keyword is added to its definition to enable it to modify its properties.

Note that you cannot call a mutating method on a constant of structure type, because its properties cannot be changed, even if they are variable properties, as described in Stored Properties of Constant Structure Instances:

// this will report an error