source

[NSObject description]의 Swift는 무엇입니까?

itover 2023. 4. 17. 21:44
반응형

[NSObject description]의 Swift는 무엇입니까?

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의 REP 출력은 도움이 됩니다.

  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

더 좋은 방법이 있을까요?

이를 Swift 타입으로 구현하려면CustomStringConvertibleprotocol을 실행한 다음 또한 다음과 같은 문자열 속성을 구현합니다.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'를 쓰는 대신 현재 인스턴스의 유형을 가져옵니다.

사용 예CustomStringConvertible그리고.CustomDebugStringConvertible프로토콜(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" 
    }

            ...
}

View Controller.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클래스 또는 그에 준거하게 하다CustomStringConvertible그리고.CustomDebugStringConvertible프로토콜입니다.

그냥 사용하다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))"
}

에 관한 답변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!"
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

여기에 설명된 대로 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
    }
}
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

언급URL : https://stackoverflow.com/questions/24108634/what-is-the-swift-equivalent-of-nsobject-description

반응형