19. • 何時選擇 Value type? 何時選擇 Reference type?
- 當你使用的 Framework 裡面有很多繼承自 NSObject 的物件,那
你就必須使用 class.
• 使用 Value Type 的時機
- 當你在比較兩個實例使用 “==” 比較合理的時候
- 你希望被拷貝的物件和原始物件互相獨立
- 當你的資料會被用在多執行緒 (multiple threads) 的時候
• 使用 Reference Type 的時機
- 比較兩個實例時使用 “===” 比較合理的時候
- 你的物件希望能被共用,或有可能有不同狀態
• 在 Swift 裡面, Array, String, Dictionary 是 Value Types。他們的
操作就如同 int value 在 C 語言一樣。這個特定讓你在拷貝資料在不
同 threads 的時候,不用特別處理同步的問題。(原文如下)
(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.)
https://developer.apple.com/swift/blog/?id=10
20. 試試看這個
• 已知在 Swift 裡面, Array 是 value type.
• 如果我在裡面塞 class。
• 從這個 Array 再複製出另一個 Array ( let arrayB = arrayA)
• 問題: 改變後來出現的 Array 裡面的 class 的 property ,第
一個 Array 裡面的 class property 會不會變?