LoginSignup
2
2

More than 5 years have passed since last update.

モデルのdescription実装を楽する

Last updated at Posted at 2016-08-17

CustomStringConvertible の extension を実装して、 description の実装を楽にします。

自作クラスを print() に入れた時に中の値を出して欲しい場合は、CustomStringConvertible を採用し description プロパティを実装する必要があります。

けれど、毎回何度も似たようなコードを書くのは面倒なので、protocol を extension できないか試したらとりあえず直近のモデルでは出力できたので、コード置いときます。

extension CustomStringConvertible {
    public var description: String {
        let mirror = Mirror(reflecting:self)
        var result = String(mirror.subjectType) + "{"
        for case let(label?, value) in mirror.children {
            result += " ,\(label):\(value)"
        }
        return result.stringByReplacingOccurrencesOfString("{ ,", withString: "{") + "}"
    }
}
2
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
2
2