Intro
During the course, a lot of swift details are touched from Lesson 1 to 3 and the classical MVC is practised in Lesson 3.
本篇侧重swift的强类型特性以及struct的特点。
Strong type language
Swift is smart enough to know the type and you can ommit the type in decalaring, function parameters and son on. For example, instance declaring:
var userIsInTheMiddleOfTypingANumber: Bool = false
var userIsInTheMiddleOfTypingANumber = false
Because in swift class, all the instances need an intialization and swift can infer the instance type from its value.
Below is the example for Array
and Dictionary
declaring:
var testStack = [Int]() // perferred style
var testStack = Array<Int>()
var testDic = [String : Int]() // perferred style
var testDic = Dictionary<String, Int>()
class && struct
In swift, many data structures are struct
, like Int
, Array
and Dictionary
, etc. It’s much different from that in Obj-C
since Array
and Dictionary
and so on are class
.
However, in swift, struct
is much like class
, and it can have func
and computed property
just like class
does. The differences are :
- only
class
can have inherition struct
is passed by value as parameters whileclass
is passed by reference
Here we talk a little more about struct
passed by value.
func testFunc(operand: [Int])
In testFunc
, there will be a copy of operand
and this copy is immutable. Why? The reason is that ther is always a hidden let
before every func’s parameter. As a result, if we want to do something on the Array, we need make it mutable, like:
func testFunc(operand: [Int])
{
var localOperand = operand //1
let op = localOperand.removeLast() //2
}
In Line 1, there is a local copy of operand
and localOperand
is mutable. Although there is a copy, swift may not do the really copy of operand
in implementation and swift may still make a reference of that array. In this way, it can be much effency.
In Line 2, we make changes on localOperand
, and at this time swift still not do a copy. It can only remember the change and reuse the unchanged one. It is really amasing when I first learn it and it indicates swift is a smart enough language.
All in all, swift is really a smart language and is valuable to learn!
Comments