Generic Initializer

init(describing:)

Creates a string representing the given value. 与えられた値を表している文字列を作成します。

Declaration 宣言

init<Subject>(describing instance: Subject) where Subject : CustomStringConvertible

Discussion 解説

Use this initializer to convert an instance of any type to its preferred representation as a String instance. The initializer creates the string representation of instance in one of the following ways, depending on its protocol conformance: このイニシャライザを使って、何らかの型のインスタンスをそれのより好まれる表現であるStringに変換してください。イニシャライザは、instanceの文字列表現をそれのプロトコル準拠に依存して以下の方法の1つで作成します:

  • If instance conforms to the TextOutputStreamable protocol, the result is obtained by calling instance.write(to: s) on an empty string s. instanceが準拠するのがTextOutputStreamableプロトコルならば、結果はinstance.write(to: s)を空の文字列s上で呼び出すことによって入手されます。

  • If instance conforms to the CustomStringConvertible protocol, the result is instance.description. instanceが準拠するのがCustomStringConvertibleプロトコルならば、結果はinstance.descriptionです。

  • If instance conforms to the CustomDebugStringConvertible protocol, the result is instance.debugDescription. instanceが準拠するのがCustomDebugStringConvertibleプロトコルならば、結果はinstance.debugDescriptionです。

  • An unspecified result is supplied automatically by the Swift standard library. 未指定の結果はSwift標準ライブラリによって自動的に提供されます。

For example, this custom Point struct uses the default representation supplied by the standard library. 例えば、このあつらえのPoint structは、標準ライブラリによって提供される省略時の表現を使います。


struct Point {
    let x: Int, y: Int
}


let p = Point(x: 21, y: 30)
print(String(describing: p))
// Prints "Point(x: 21, y: 30)"

After adding CustomStringConvertible conformance by implementing the description property, Point provides its own custom representation. CustomStringConvertible準拠をdescriptionプロパティの実装によって加えた後、Pointはそれ独自のあつらえの表現を提供します。


extension Point: CustomStringConvertible {
    var description: String {
        return "(\(x), \(y))"
    }
}


print(String(describing: p))
// Prints "(21, 30)"

See Also 参照

Converting Other Types to Strings 他の型を文字列に変換する