Qual è l'equivalente di Swift di - [descrizione NSObject]?


163

In Objective-C, è possibile aggiungere un descriptionmetodo alla loro classe per facilitare il debug:

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

Quindi nel debugger puoi fare:

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

Qual è l'equivalente in Swift? L'output REPL di Swift può essere utile:

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

Ma vorrei ignorare questo comportamento per la stampa sulla console:

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

C'è un modo per ripulire questo printlnoutput? Ho visto il Printableprotocollo:

/// 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 }
}

Ho pensato che questo sarebbe automaticamente "visto" da printlnma non sembra essere il caso:

  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)

E invece devo chiamare esplicitamente la descrizione:

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

C'è un modo migliore?

Risposte:


124

Per implementarlo su un tipo Swift è necessario implementare il CustomStringConvertibleprotocollo e quindi implementare anche una proprietà stringa chiamata description.

Per esempio:

class MyClass: CustomStringConvertible {
    let foo = 42

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

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

Nota: type(of: self)ottiene il tipo di istanze correnti invece di scrivere esplicitamente "MyClass".


3
Grande scoperta! Ho intenzione di presentare un radar - l'output di stampa di "swift -i sample.swift" e "swift sample.swift && sample" differisce.
Jason,

Grazie per le informazioni a riguardo. Stavo provando Stampabile in un parco giochi e in effetti non funziona in questo momento. Bene, sente che funziona in un'app.
Tod Cunningham,

Stampabile funziona nel parco giochi, ma se la classe discende da NSObject
dar512

5
In Swift 2.0 è stato modificato in CustomStringConvertible e CustomDebugStringConvertible
Mike Vosseller,

Inoltre, non ci sono problemi con CustomStringConvertible e CustomDebugStringConvertible in Playground con Xcode 7.2
Nicholas Credli

54

Esempio di utilizzo CustomStringConvertiblee CustomDebugStringConvertibleprotocolli in Swift:

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)
    }

          ...
}

Quale stampa:

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

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

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

Nota: se si dispone di una classe personalizzata che non eredita da alcuna classe inclusa nelle librerie UIKit o Foundation , renderla ereditaria della NSObjectclasse o renderla conforme CustomStringConvertiblee CustomDebugStringConvertibleprotocolli.


la funzione deve essere dichiarata pubblica
Karsten

35

Basta usare CustomStringConvertibleevar description: String { return "Some string" }

funziona in Xcode 7.0 beta

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

Le risposte relative a CustomStringConvertiblesono la strada da percorrere. Personalmente, per mantenere la definizione di classe (o struttura) il più pulita possibile, vorrei anche separare il codice di descrizione in un'estensione separata:

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

Come descritto qui , puoi anche usare le capacità di riflessione di Swift per fare in modo che le tue classi generino la loro descrizione usando questa estensione:

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
Utilizzando il nostro sito, riconosci di aver letto e compreso le nostre Informativa sui cookie e Informativa sulla privacy.
Licensed under cc by-sa 3.0 with attribution required.