Swift tips and tricks

Passing messages around view controllers

  • 三种在view controllers中传递参数的方法,Delegation pattern, Notifications, Closures and action handlers。可以在这篇帖子中找到。

CS193P open course notes

  1. MVC
  2. Swift Programming Language
  3. More Swift
  • Please find all relevant materials for Standford Programming course cs193p in here

MVC communication

MVC

  • Controller can talk to both Model and View. But Model and View should never speak to each other. For the View, it can communicate to the Controller, but in certain ways. Because View are all generic UI objects, to change some of its properties to fits the app’s objective, we need to send the UI objects, like buttons and labels back to the controller, let controller to implement its properties like background color, label content etc… so we use Action method to target the function that will be calling when certain UI objects are triggered. Another way to talk to controller is to use Delegate, for more complicated objects like scroll view or tables, we need to let controller know what we are doing at the moment, and controller is responsible for implementing the extra tasks while we are doing this things. Another important thing is that views do not own the data they display, they ask for the controller and controller grab the data from Data source and give it to the View, because if you have 50000 songs in a table, if table owns the data, it will be too big and costy to create such table object. So instead we use Data Source to provide data to the view.

MVC communication

  • What about Model, can Model talk to the Controller? Yes, but not directly, because Model is UI independent, and Controller is UI dependent, so if a Model is updated and he wants everybody that is interested to be informed, it will broadcast this information to all the controllers, and those controllers that are listening will be notified and talk to Model and grab the changes. This way is called notifications

MVC communication

  • One MVC model usually controls one screen on iPhone, and when multiple MVCs are talking to each other, they often treats other MVC as its View. So when one Screen wants to talk to another Screen, it uses delegate!

MVC communication

  • Do not implement your app this way!

struct and class

  • They are similar, contains methods and variables, but struct has no inheritance, Another difference is structs are value types, and classes are reference types, so when we assign it to another variable, it gets copied. Arrays, ints, strings, dictionary are all structs, but swift doesn’t make a copy of all of them when we need it, it only copy them when a user modifies it. It’s called copy-on-write semantics. For classes, we do not make a copy of it when we need it, we make a reference to the class, so when we modify the properties of that class, the real class gets modified too.

  • Try not to use initialiser in the view controller

stride

stride

  • In swift, we don’t have for(; 😉 structrue, so we need stride method for a range with specific count value

tuples

Swift Programming Language

tuples

  • They are nothing but a group of values, different types of values could be inside the same tuple, vars and methods are not allowed in tuples, its good for return multiple values from a method because a method can only return a single thing.

Computed properties

  • stored properties(normal properties) and computed properties

  • Computed properties are properties with get and set methods, you can have read only computed properties, which only has get method. get and set part will be executed when we get or set the variable.

  • we use computed property because sometimes we can derive property from other place, like indexOfOneAndOnlyFaceUpCard GET can be derived by looking at all the cards and see if you can get only one card facing up and return that index. And SET can give the card that is facing up to the property. You can omit the GET word if it is a read only computed property

Access control

Access control

  • Protecting our internal implementations, by only give other people names of the methods that are allowed to be called.

  • Internal: usable by any object in my app or framwork, its default

  • private: callable only within this object

  • private(set): means its only readable from outside the object, but not settable

  • filePrivate: accessiable by any object in this source file

  • public(for frameworks only): can be used by object outside this framework

  • open(for frameworks only): public AND can sub-class(override)

  • assertion: a method that in your program when you assert something is true, is not, the app will crash. It is a good way to protect your API.

Extension

  • Add vars and methods to other classes even if you don’t have the source.

  • But there are restrictions: you can’t re-implement the methods that are already there. You can only add new ones. And, properties you add can have no stroage associated with them.(computed only)

Enum

  • Another variety of data structrue apart from struct and class. It can only have discrete states. Enum is a VALUE type, like structs, so it gets copied as it is passed around. Enum in Swift can have an associated data.

Enum with associated value

  • Enum with associated value

Enum

  • Checking enum’s state with Switch cases syntax

Enum

  • using associated value in switch cases

Enum

  • Enum can have methods, and you can test a enum’s state within that method with self keyword

Enum

  • You can even change the enum’s state in its methods, by giving that method a mutating keyword to let Swift know.

Optionals

  • Optional is just an enum, it has two cases, one is nil, which measns it is not set yet, the other is some, which means it has some associated value with it. If you are trying to force unwrap an optional, what Swift really do it just throw an exception when that enum is in case nil, and do whatever you want to do with that enum in case ‘some’.

Optional
Optional
Optional
Optional

Memory Management

Class

  • Automatic reference counting: Reference types are stored in the heap, everytime you create a pointer to a reference type in the heap, Swift will add One to a counter for that reference type, everytime when a pointer goes out of scope, Swift decrement the counter. And when the counter decrement to zero, Swift will instantly remove that reference type out of heap.

  • Influence ARC by using ‘strong’, ‘weak’ and ‘unowned’

structs

  • structs

More Swift

protocol

  • Protocol is the fourth data structure in Swift. It is basically a type, which contains a list of variables and a list of methods, without implementation. Any class or structs or enum that want to inherit protocol must implement all methods declared in that protocol. But, for objective C methods, implementations are optional. This is why when we override some will, did, set methods for some UI obejcts, we dont need to implement all methods from that protocol.

protocol mutating

  • Mutating functions: in protocol, some functions may be marked as mutating, when structs trying to inherit a protocol, because structs are value types, so structs get copied when we want to use it. However, it would be very inefficient if we make a copy every time we see it. So Swift uses copy-on-write system, we only make a copy of that struct when we are trying to modify it, in other words, mutating it. So we a struct is trying to change something in a function, and that function is inherted from a protocol, then this function has to be marked as mutating.

protocol init

protocol init required

  • Init: init functions are allowed to exist in protocol, however, in a class inherited that protocol, we need to add requried keyword before init function, this is because this class could have some other subclasses, and these classes also have to implement init function.

protocol type

  • Use protocol as a type

protocol delegation

  • Delegation: a very important use of protocol is delegation.

protocol multiple inheritance

  • Mutiple inheritance: if you want to use certain functions in some protocols, you could inherit that protocol and implement the functions you want to use.