LoginSignup
22
13

More than 5 years have passed since last update.

CustomStringConvertibleについて

Last updated at Posted at 2016-08-14

インスタンスプロパティをprint関数でデバッグエリアに表示させたかったので調べてみた。
クラスを以下のプロトコルに適合することによって実装できるみたい。
(表示できない理由はクラスの特性であるカプセル化の働きで、外部からインスタンスプロパティがどんな値を持っているか隠蔽しているため。だという認識だけどあってるかな。。。)

CustomStringConvertible

UIKitに定義されているProtocolで、descriptionというプロパティが定義されている。

public protocol CustomStringConvertible {
    /// A textual representation of `self`.
    public var description: String { get }
}

使ってみた

import UIKit
//クラスを適合させる
class Example: CustomStringConvertible{

    let name: String
    //descriptionに表示したい文字列を定義する
    var description: String { return "nameの値は\(name)です" }
    //初期化
    init(name: String) {
        self.name = name
    }

}
//インスタンス化
var example = Example(name: "AAA")

print(example)


//結果 descriptionで定義された文字列が表示されるみたい
//nameの値はAAAです

ちなみに実装前

import UIKit

class Example {

    let name: String

    init(name: String) {
        self.name = name
    }

}

var example = Example(name: "AAA")

print(example)

//結果 クラス名が表示された
//Example

// A textual representation of self......
selfを文字通り表現する....
そういうこと?
実装前のprint結果でクラス名が表示されてるから、それをdescriptionで定義した文字列に置き換えますよってことか!!
なんかスッキリ。

普通に読み飛ばしてたつらい。
難なく英語読めるようになりたい。

まとめ

descriptionで定義した文字列が表示されるみたい。
文字列の中に確認したいプロパティを組み込めばOK。
今回の件で曖昧な理解だったカプセル化についての理解も深まった(若干)。

22
13
1

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
22
13