2017年3月27日 星期一

Swift : Let & Var, ! & ? Optional (Wrapped & unwrapped) 驚嘆號 問號

發現以單一功能性app的小型開發學習法,過於缺乏系統性與效率,於是在網路上找到了CS193P這個課程,我打算上完這一系列的課程,並且在學習過程中持續複習C++的資結。

這個課程可以在iTune U找到且免費。其包含了所有課程 slides & homeworks,我也將會全部完成。

Let. 1 notes:

  • Let & Var
The let keyword defines a constant:
let theAnswer = 42
The theAnswer cannot be changed afterwards. <-- This is why anything optional or weak can't be written using let. They need to change during runtime and must be wrote using var.
The var defines an ordinary variable:
What is interesting:
The value of a constant doesn’t need to be known at compile time, but you must assign it a value exactly once.
Another strange feature:
You can use almost any character you like for constant and variable names, including Unicode characters:
let 🐶🐮 = "dog cow"
credit: community wiki @stackoverflow 
  • ! & ? Optional (Wrapped & unwrapped)
In a type declaration the ! is similar to the ?. Both are an optional, but the ! is an "implicitly unwrapped" optional, meaning that you do not have to unwrap it to access the value (but it can still be nil).
This is basically the behavior we already had in objective-c. A value can be nil, and you have to check for it, but you can also just access the value directly as if it wasn't an optional (with the important difference that if you don't check for nil you'll get a runtime error)
// Cannot be nil
var x: Int = 1

// The type here is not "Int", it's "Optional Int"
var y: Int? = 2

// The type here is "Implicitly Unwrapped Optional Int"
var z: Int! = 3

Usage:

// you can add x and z
x + z == 4

// ...but not x and y, because y needs to be unwrapped
x + y // error

// to add x and y you need to do:
x + y!

// but you *should* do this:
if let y_val = y {
    x + y_val
}
credit: Jiaaro  

Swift GitBook about Optional
  • Computed properties 
我自己程式中的應用:
    var displayValue: Double {
        get {
            return Double(display.text!)!
        }
        set {
            display.text = String(newValue)
        }
    }
當使用displayValue 時,判定其作用在於get值或是set值,並且進行相對應的implementation,像是回傳一個casting完的值,或是將特定值casting完並輸出。此處的newValue是個需要注意的特殊用法,代表任何與本函數同樣性質的物件(?)

supplement:
useful materials


沒有留言:

張貼留言