1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

玩玩 @propertyWrapper

Last updated at Posted at 2020-01-20

看了這兩篇文章動手做之後簡單來做個筆記

規格 提案

SE-0258 Property Wrappers

小聲說:寫這篇的時候我還沒詳細讀完所有的內容

玩過之後看到的優點

  • 過去以來需要寫在 didSet 裡面的邏輯有辦法再封裝,讓宣告的地方能夠更加乾淨
  • 似乎可以解決在設定初始值無法觸發 didSet 的問題

語法

對我來說,直覺是有 Java 中 annotation 的 fu
詳細說明可以參照

定義

@propertyWrapper
struct Trimmed {
    private(set) var value: String = ""
    
    // 根據文件指出,「必須」定義這個 property 
    var wrappedValue: String {
        get { value }
        set { value = newValue.trimmingCharacters(in: .whitespacesAndNewlines) }
    }
    
    init(wrappedValue: String) {
        self.wrappedValue = wrappedValue
    }
}

wrappedValue 通常會是一個 computed value ,用這樣的寫法的話,在 set 裡面可以拿到在 init 中被設定的值,而 get 中回傳的值則是放處理完成的值。

使用方式

先定義一個簡單的 struct 並把剛剛定義的 property wrapper 放在一個屬性前面

struct Post {
    @Trimmed var title: String
}

使用之後如下:

let post = Post(title: " B A A ")
print(post.title) // "B A A"

因為有透過 property wrapper 的處理,這時候在 console 輸出的內容會是 B A A ,而不是前後有空白的 B A A

目前還沒摸清楚可以在實際專案中怎麼用,不過看來是個可以拿來做適度封裝的好工具。
接下來還要繼續去看 Projected Value 到底是什麼東西和可以怎麼用,看懂之後再來多寫一篇。

環境

  • Xcode 11.3.1
  • Swift 5.1
  • Playground

參考

1
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?