LoginSignup
1
2

More than 3 years have passed since last update.

SwiftのProperty Wrappers 機能を使って自作の @-prefixed attributes.を作ってみた

Last updated at Posted at 2020-07-03

概要

表題の通りであります。

引用

NSHiper

Sample code

入力文字列値から空白と改行を削除する次のprefixed attributesのサンプルが下記になります。

@propertyWrapper を利用して、定義します。


import Foundation

@propertyWrapper
struct Trimmed {
    private(set) var value: String = ""

    var wrappedValue: String {
        get { value }
        set { value = newValue.trimmingCharacters(in: .whitespacesAndNewlines) }
    }

    init(wrappedValue initialValue: String) {
        self.wrappedValue = initialValue
    }
}

使ってみる。

struct Post {
    @Trimmed var title: String
    @Trimmed var body: String
}

var quine = Post(title: "  Swift Property Wrappers  ", body: "…")

print(quine.title)// Swift Property Wrappers 

こんな感じでいけます。

airbnbがよしなにやっていたので、勉強してみました。

airbnb github
https://github.com/airbnb/ResilientDecoding

コードと解説はNSHiperをそのまま引用しました、詳しい情報はNSHiperApple (github)を参考にして下さい。

1
2
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
2