MVC
- Model
- Never communicate with View.
- Send message to controller by notification center or KVO.
- View
- Never communicate with Model.
- Send message to controller by user action(ie IBAction), delegate or data source methods(ie asking for new data when tableview scrolling).
Controller
- Can access model directly to get data, and control view to update in specfic way directly, too.
- Model / view use indirect ways to send messages to controller as previous mentioned.
The differences between struct and class
Major
- struct has NO inheritance.
- When we assigned a struct to another variable, it copies it. Putting them in an array or taking them out also coppies. Namely, struct pass argument by sending a copy of value. If the value of new var is modified, the origin var will remain the same value.
- Class pass arguments by reference.
Minor
- Init: Struc and class both gets free initializers but
- struc: intializes ALL of their vars in default. We have to rewrite the init method to avoid giving all parameters everytime while init an object og struct.
- class
Static function
Static function means we send messages to the “Type name” but NOT the “Object name”, so use type name to call static function, NOT to use object to call static function.
|
|
While using static var in the static method, we no need to add the type name as preffix.
_
(Under bar)
The under bar _
in Swift means not important thing, we don’t care about what is it.
|
|
The _
in the above statement means we do not need the counter, but just need to do something repeated.
Property observer
Use didSet
function in property definition to observe the value change, this func calls everytime when the variable changed.
|
|
I’ll print out variable touchCount
‘s value everytime when touchCount
is changed.
?
(Question mark)
Question mark indicates “optional”, it means var either contains a value or just be nil
, often use together with if
and let
statement. For example:
|
|
If we execute the code above, it’ll print “Hello, SHY” because myName
has a value.
In convenience, we’ll write the following code:
|
|
as:
|
|
for we have to check variables frequently.
Initial
All property initializers run BEFORE class’ self
is available, so we can’t use instance member within property intialize.
One cool way to solve this problem is use lazy var
instead of var
to declare variable which we attend to init. If we make a var lazy
, that means it do not intialize until someone grab it. But remember, lazy var
cat not use property observer such as didSet
method in the init function.
if
statement
The statement of describing if A && B {...}
in Swift:
|
|
we can “read” Swift code just like an English article.
References
visit iTunes U app in App store and search for the class name – Developing iOS 11 Apps with Swift (Stanford)