Swiftで-[NSObject description]に相当するものは何ですか?


163

Objective-Cではdescription、デバッグに役立つメソッドをクラスに追加できます。

@implementation MyClass
- (NSString *)description
{
    return [NSString stringWithFormat:@"<%@: %p, foo = %@>", [self class], foo _foo];
}
@end

次に、デバッガーで次のことができます。

po fooClass
<MyClass: 0x12938004, foo = "bar">

Swiftで同等のものは何ですか?SwiftのREPL出力は役に立ちます:

  1> class MyClass { let foo = 42 }
  2> 
  3> let x = MyClass()
x: MyClass = {
  foo = 42
}

しかし、コンソールに出力するためにこの動作をオーバーライドしたいと思います。

  4> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)

このprintln出力をクリーンアップする方法はありますか?私はPrintableプロトコルを見てきました:

/// This protocol should be adopted by types that wish to customize their
/// textual representation.  This textual representation is used when objects
/// are written to an `OutputStream`.
protocol Printable {
    var description: String { get }
}

これは自動的に「見られる」と考えましたprintlnが、そうではありません。

  1> class MyClass: Printable {
  2.     let foo = 42
  3.     var description: String { get { return "MyClass, foo = \(foo)" } }
  4. }   
  5> 
  6> let x = MyClass()
x: MyClass = {
  foo = 42
}
  7> println("x = \(x)")
x = C11lldb_expr_07MyClass (has 1 child)

そして代わりに私は明示的に説明を呼び出​​さなければなりません:

 8> println("x = \(x.description)")
x = MyClass, foo = 42

もっと良い方法はありますか?

回答:


124

これをSwiftタイプに実装するには、CustomStringConvertibleプロトコルを実装してから、という文字列プロパティを実装する必要がありますdescription

例えば:

class MyClass: CustomStringConvertible {
    let foo = 42

    var description: String {
        return "<\(type(of: self)): foo = \(foo)>"
    }
}

print(MyClass()) // prints: <MyClass: foo = 42>

注:type(of: self)明示的に「MyClass」を書き込む代わりに、現在のインスタンスのタイプを取得します。


3
素晴らしい発見!レーダーを提出します。「swift -i sample.swift」と「swift sample.swift && sample」のprintln出力は異なります。
Jason

その情報をありがとう。私は遊び場でPrintableを試してみましたが、実際には現在動作しません。アプリで機能するようです。
トッドカニンガム2014年

Printableは遊び場でも機能しますが、クラスがNSObjectから
派生している場合を除きます

5
Swift 2.0では、CustomStringConvertibleおよびCustomDebugStringConvertibleに変更されました
Mike Vosseller '12 / 09/15

また、Xcode 7.2のPlaygroundでCustomStringConvertibleとCustomDebugStringConvertibleを使用しても問題はありません
Nicholas Credli

54

Swift CustomStringConvertibleでのCustomDebugStringConvertibleプロトコルと使用例:

PageContentViewController.swift

import UIKit

class PageContentViewController: UIViewController {

    var pageIndex : Int = 0

    override var description : String { 
        return "**** PageContentViewController\npageIndex equals \(pageIndex) ****\n" 
    }

    override var debugDescription : String { 
        return "---- PageContentViewController\npageIndex equals \(pageIndex) ----\n" 
    }

            ...
}

ViewController.swift

import UIKit

class ViewController: UIViewController
{

    /*
        Called after the controller's view is loaded into memory.
    */
    override func viewDidLoad() {
        super.viewDidLoad()

        let myPageContentViewController = self.storyboard!.instantiateViewControllerWithIdentifier("A") as! PageContentViewController
        print(myPageContentViewController)       
        print(myPageContentViewController.description)
        print(myPageContentViewController.debugDescription)
    }

          ...
}

どのプリントアウト:

**** PageContentViewController
pageIndex equals 0 ****

**** PageContentViewController
pageIndex equals 0 ****

---- PageContentViewController
pageIndex equals 0 ----

注:UIKitまたはFoundationライブラリに含まれているクラスから継承しないカスタムクラスがある場合は、クラスを継承するか、プロトコルNSObjectに準拠するようにCustomStringConvertibleCustomDebugStringConvertibleます。


関数はpublicとして宣言する必要があります
Karsten

35

使用CustomStringConvertibleしてvar description: String { return "Some string" }

Xcode 7.0ベータで動作します

class MyClass: CustomStringConvertible {
  var string: String?


  var description: String {
     //return "MyClass \(string)"
     return "\(self.dynamicType)"
  }
}

var myClass = MyClass()  // this line outputs MyClass nil

// and of course 
print("\(myClass)")

// Use this newer versions of Xcode
var description: String {
    //return "MyClass \(string)"
    return "\(type(of: self))"
}

20

関連する答えCustomStringConvertibleは行く方法です。個人的には、クラス(または構造体)の定義をできるだけクリーンに保つために、説明コードを個別の拡張子に分離します。

class foo {
    // Just the basic foo class stuff.
    var bar = "Humbug!"
}

extension foo: CustomStringConvertible {
    var description: String {
        return bar
    }
}

let xmas = foo()
print(xmas)  // Prints "Humbug!"

8
class SomeBaseClass: CustomStringConvertible {

    //private var string: String = "SomeBaseClass"

    var description: String {
        return "\(self.dynamicType)"
    }

    // Use this in newer versions of Xcode
    var description: String {
        return "\(type(of: self))"
    }

}

class SomeSubClass: SomeBaseClass {
    // If needed one can override description here

}


var mySomeBaseClass = SomeBaseClass()
// Outputs SomeBaseClass
var mySomeSubClass = SomeSubClass()
// Outputs SomeSubClass
var myOtherBaseClass = SomeSubClass()
// Outputs SomeSubClass

6

ここで説明するように、Swiftのリフレクション機能を使用して、この拡張機能を使用することにより、クラスに独自の説明を生成させることもできます。

extension CustomStringConvertible {
    var description : String {
        var description: String = "\(type(of: self)){ "
        let selfMirror = Mirror(reflecting: self)
        for child in selfMirror.children {
            if let propertyName = child.label {
                description += "\(propertyName): \(child.value), "
            }
        }
        description = String(description.dropLast(2))
        description += " }"
        return description
    }
}

4
struct WorldPeace: CustomStringConvertible {
    let yearStart: Int
    let yearStop: Int

    var description: String {
        return "\(yearStart)-\(yearStop)"
    }
}

let wp = WorldPeace(yearStart: 2020, yearStop: 2040)
print("world peace: \(wp)")

// outputs:
// world peace: 2020-2040
弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.